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.   
  5. extern "C"  
  6. {  
  7.     void test() {  
  8.          cout << "TEST" << endl;  
  9.     }  
  10.   
  11.     int addTest(int a,int b)  
  12.     {  
  13.       int c = a + b ;  
  14.       return c ;  
  15.     }   
  16. }  


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

2.JAVA代码

 1         import com.sun.jna.Library;  
 2         import com.sun.jna.Native;  
 3           
 4         public class jnatest1 {  
 5           
 6             // 继承Library,用于加载库文件  
 7             public interface Clibrary extends Library {  
 8                 // 加载libhello.so链接库  
 9                 Clibrary INSTANTCE = (Clibrary) Native.loadLibrary("hello",  
10                         Clibrary.class);  
11           
12                 // 此方法为链接库中的方法  
13                 void test();  
14                 int addTest(int a,int b);    
15             }  
16           
17             public static void main(String[] args) {  
18                 // 调用  
19                 Clibrary.INSTANTCE.test();  
20                 int c = Clibrary.INSTANTCE.addTest(10,20);    
21                 System.out.println(c);   
22             }  
23         } 

 

原文地址:https://www.cnblogs.com/LiuYanYGZ/p/6109579.html