摘自: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++方法。
- #include <stdlib.h>
- #include <iostream>
- using namespace std;
- extern "C"
- {
- void test() {
- cout << "TEST" << endl;
- }
- int addTest(int a,int b)
- {
- int c = a + b ;
- return c ;
- }
- }
我把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 }