前言
相关环境:Windows10,VS2013,IDEA2020,JDK1.8x64
JNI的相关示例demo:JNI的使用和示例
1、JNA
JNA(Java Native Access)框架是一个开源的Java框架,是SUN公司主导开发的,建立在经典的JNI的基础之上的一个框架。
2、windows环境下构建dll
2.1、新建项目
新建项目时选择win32项目。
勾选DLL选项。
2.2、实现函数
直接在自动生成的项目名同名的cpp文件中添加需要导出的函数。
函数名前面extern "C" __declspec(dllexport)
必须加,不然JNA调用时找不到该函数名。
2.3、修改平台
添加x64平台。
最终效果
2.4、生成dll
生成解决方案生成动态库。
找到项目路径。
dll在x64目录下。
3、Linux环境下构建so
C语言源文件
makefile文件
直接执行make命令生成so文件。或者执行gcc -fPIC -shared -o libhello.so hello.c。
4、JAVA调用JNA
package cn.weezoo.jnademo;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
/**
* @author wenei
* @date 2021-02-25 18:33
*/
public class JNATest {
private static final String filePath;
static {
if (Platform.isWindows()) {
System.out.println("Windows platform");
// windows平台最前面的路径需要去掉一个/
filePath = Thread.currentThread().getContextClassLoader().getResource("libhello.dll").getPath().substring(1);
} else if (Platform.isLinux()) {
System.out.println("Linux platform");
filePath = Thread.currentThread().getContextClassLoader().getResource("libhello.so").getPath();
} else {
System.out.println("Other platform");
filePath = null;
}
}
interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary) Native.loadLibrary(filePath, CLibrary.class);
void hello();
}
public static void main(String[] args) {
CLibrary instance = CLibrary.INSTANCE;
instance.hello();
}
}
4.1、注意
1、在Linux平台下运行jar时,需要将jna.jar一同运行使用。不然找不到com.sun.jna.Native;
windows平台直接使用IDEA运行即可。
2、如果C中的函数返回char,如果是加密操作,密文可能会有\0在中间,在java中调用时地址会不一样,即返回的字符串不一致。所以函数不要将密文当做返回值,直接加一个接收参数,然后java中使用byte[]进行接收。*