话不多说,直接进入重点。

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);
    }

结果:

在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐