linux下java调用.so动态库方法2: JNA

时间:2023-03-09 06:29:02
linux下java调用.so动态库方法2: JNA

摘自:http://blog.csdn.net/todorovchen/article/details/21319033

另请参见: http://blog.sina.com.cn/s/blog_8cfbb9920100zy7g.html

LINUX 下 JNA 调用 so--正确版

项目中需要用到Java调用c++,了解过JNI,但比较复杂,后来看到JNA(JNI的加强版)。

网上看了很多例子,但是始终出错,主要错误原因是undefined symbol,找不到c++ 方法。

教程的有些细节没说(- -||),好吧,我把成功的例子贴一下吧。

1.编写C++ so库

c++代码:注意加上extern “C”,否则无法找到c++方法。

  1. #include <stdlib.h>
  2. #include <iostream>
  3. using namespace std;
  4. extern "C"
  5. {
  6. void test() {
  7. cout << "TEST" << endl;
  8. }
  9. int addTest(int a,int b)
  10. {
  11. int c = a + b ;
  12. return c ;
  13. }
  14. }
linux下java调用.so动态库方法2: JNA

我把so文件放到了 /lib 下。

2.JAVA代码

         import com.sun.jna.Library;
import com.sun.jna.Native; public class jnatest1 { // 继承Library,用于加载库文件
public interface Clibrary extends Library {
// 加载libhello.so链接库
Clibrary INSTANTCE = (Clibrary) Native.loadLibrary("hello",
Clibrary.class); // 此方法为链接库中的方法
void test();
int addTest(int a,int b);
} public static void main(String[] args) {
// 调用
Clibrary.INSTANTCE.test();
int c = Clibrary.INSTANTCE.addTest(10,20);
System.out.println(c);
}
}