话不多说,直接进入重点。
1. 导入jna依赖
<dependency>
<groupId>com.sun.jna</groupId>
<artifactId>jna</artifactId>
<version>3.0.9</version>
</dependency>
2. 在resources下新建目录linux-x86-64,并在这个目录中放入so文件

3. 调用如下初始化代码,多个so调用时请自行封装
static {
try {
String path = System.getProperty("java.io.tmpdir");
String name = "libmath.so";
// 获取sources下的资源
ClassPathResource classPathResource = new ClassPathResource("linux-x86-64/" + name);
InputStream in = classPathResource.getInputStream();
// 写入到临时文件
FileUtil.writeFile(path + "/lib/" + name, in);
} catch (IOException e) {
//
}
}
4. 建立Math.class映射
package com.xxx.jni;
import com.sun.jna.Library;
import com.sun.jna.Structure;
public interface Math extends Library {
int max(int a, int b);
class TestStruct extends Structure {
public static class ByReference extends TestStruct implements Structure.ByReference {
}
public static class ByValue extends TestStruct implements Structure.ByValue {
}
}
}
调用:
@PostMapping("/A0018")
public ServerResponse A0018() {
String path = System.getProperty("java.io.tmpdir");
Math mathJNI = (Math) Native.loadLibrary(path + "/lib/" + name, Math.class);
int max = mathJNI.max(5432, 211233);
return ServerResponse.success(max);
}
结果:

本文介绍了如何在Java项目中通过JNA库加载Linux平台的动态链接库(so文件),包括依赖引入、资源管理及实际的JNI接口调用示例。重点在于如何将so文件正确地加载到Java应用中并实现功能调用。
4177





