我有一個C++庫xyz。它有很多類,如xyzA
,xyzB
等我想要使用類xyzA
在xyz庫中的方法getAge()
。使用JNI從C++庫加載特定類的方法
xyz.so
文件已存在。
步驟我都遵循:
創建一個Java類
xyz.java
class xyz { public native int getAge(); public static void main(String[] args) { new xyz().getAge(); } static { System.loadLibrary("xyz"); } }
創建的頭爲Java類。
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class xyz */ #ifndef _Included_xyz #define _Included_xyz #ifdef __cplusplus extern "C" { #endif /* * Class: xyz * Method: getAge * Signature:()I */ JNIEXPORT jint JNICALL Java_xyz_getAge (JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif
CPP的包裝類的樣子:
#include <stdio.h> #include "xyz.h" #include <jni.h> JNIEXPORT jint JNICALL Java_xyz_getAge(JNIEnv *, jobject) { // some code }
我成功編譯的類,如下所示:
gcc -fPIC -shared -l stdc++ -I/grid/0/gs/java/jdk64/current/include -I/grid/0/gs/java/jdk64/current/include/linux xyz.cpp
然後運行Java PROG爲:
java -Djava.library.path=/grid/0/tmp/direct/lib xyz
我得到以下錯誤:
Exception in thread "main" java.lang.UnsatisfiedLinkError: xyz.getAge()I at xyz.getAge(Native Method) at xyz.main(xyz.java:6)
它無法找到特定的類xyzA
方法getAge()
。如何訪問該方法?另外,圖書館是通過我的包裝類來鏈接的嗎?
任何指針,將不勝感激。
謝謝。
另一種方法是使用'System.load(String)',並提供完整的路徑和文件名。但是,遵守共享庫命名的平臺慣例仍然是一個好主意。 –
'strace'可以方便地找出jvm試圖加載的內容。 – msandiford