JNA使用入门

JNA即Java Native Access。

官方文档

使用样例

准备Java代码文件,内容来源于Getting Started,如下:

import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;

/** Simple example of JNA interface mapping and usage. */
public class HelloWorld {

    // This is the standard, stable way of mapping, which supports extensive
    // customization and mapping of Java to native types.

    public interface CLibrary extends Library {
        CLibrary INSTANCE = (CLibrary)
            Native.load((Platform.isWindows() ? "msvcrt" : "c"),
                                CLibrary.class);

        void printf(String format, Object... args);
    }

    public static void main(String[] args) {
        CLibrary.INSTANCE.printf("Hello, World\n");
        for (int i=0;i < args.length;i++) {
            CLibrary.INSTANCE.printf("Argument %d: %s\n", i, args[i]);
        }
    }
}

修改项目的pom.xml,增加如下依赖:

<!-- https://mvnrepository.com/artifact/net.java.dev.jna/jna -->
<dependency>
    <groupId>net.java.dev.jna</groupId>
    <artifactId>jna</artifactId>
    <version>5.14.0</version>
</dependency>

等待依赖下载完毕,构建完毕,运行前述样例代码。

从源码构建JNA

  • Setting up a Windows Development Environment
    在Windows环境执行构建,执行如下命令:
    cd C:\Code\jna
    
    set JAVA_HOME=C:\Tools\jdk
    set ANT_HOME=C:\Tools\ant
    set CYGWIN_HOME=C:\Tools\cygwin64
    
    set PATH=%JAVA_HOME%\bin;%ANT_HOME%\bin;%CYGWIN_HOME%\bin;%PATH%
    
    "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat" x64
    
    ant
    
    在Linux环境执行构建,执行如下命令:
    cd /path/to/jna_code
    
    export JAVA_HOME=/path/to/jdk
    export ANT_HOME=/path/to/ant
    export PATH=$JAVA_HOME/bin:$ANT_HOME/bin:$PATH
    ant
    
  • Android Development Environment
    在Linux环境执行构建,执行如下命令:
    
    cd /path/to/jna_code
    
    export JAVA_HOME=/path/to/jdk
    export ANT_HOME=/path/to/ant
    export PATH=$JAVA_HOME/bin:$ANT_HOME/bin:$PATH
    
    export NDK_PLATFORM=/path/to/android-ndk-r12b/platforms/android-21
    export PATH=$NDK_PLATFORM/../../toolchains/aarch64-linux-android-4.9/prebuilt/linux-x86_64/bin/:$PATH
    ant -Dos.prefix=android-aarch64
    

参考资料

热门相关:神医娘亲:腹黑萌宝赖上门   侯门弃女:妖孽丞相赖上门   全能王妃:偷个王爷生宝宝   军少夜宠:小甜妻,乖!   帝少夜宠:小甜妻,乖!