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         } 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM