深眸分享--java调用c/c++的so接口
2022-05-26
项目中有时候会用到不同语言的代码,例如在java中调用c/c++的借口,以ubuntu下springboot中调用so为例子,需要用到jna库,在build.gradle中添加
implementation "net.java.dev.jna:jna:5.9.0"
test.cpp中有两个方法
#
int add(int a, int b){
return a + b;
}
void hello()
{
printf("Hello World!\n");
}
在springboot项目下resouces目录创建linux-x86-64目录,把test.cpp编译成so文件,放在该文件夹,创建Test.java
import com.sun.jna.Library;
import com.sun.jna.Native;
public class Test {
public interface LibTest extends Library {
LibTest INSTANCE = Native.load("test", LibTest.class);
int add(int a, int b);
void hello();
}
public static void main(String[] args) {
System.out.println(LibTest.INSTANCE.add(1,2));
LibTest.INSTANCE.hello();
}
}
执行java文件,控制台输出
3
Hello World!