2 回答

TA貢獻1876條經驗 獲得超7個贊
在這種情況下,它非常簡單。您所要做的就是傳遞給您的本機代碼并使用基于訪問的方法List將其填充到內部JNIJNI
#include <vector>
#include "jni.h"
#include "recipeNo046_FillTheList.h"
using namespace std;
JNIEXPORT void JNICALL Java_recipeNo046_FillTheList_fillTheList
(JNIEnv *env, jclass cls, jobject obj) {
vector<int> vect { 1, 2, 3 };
jclass listClass = env->FindClass("java/util/List");
if(listClass == NULL) {
return; // alternatively, throw exception (recipeNo019)
}
jclass integerClass = env->FindClass("java/lang/Integer");
if(integerClass == NULL) {
return; // alternatively, throw exception (recipeNo019)
}
jmethodID addMethodID = env->GetMethodID(listClass, "add", "(Ljava/lang/Object;)Z");
if(addMethodID == NULL) {
return; // - || -
}
jmethodID integerConstructorID = env->GetMethodID(integerClass, "<init>", "(I)V");
if(integerConstructorID == NULL) {
return; // - || -
}
for(int i : vect) {
// Now, we have object created by Integer(i)
jobject integerValue = env->NewObject(integerClass, integerConstructorID, i);
if(integerValue == NULL) {
return;
}
env->CallBooleanMethod(obj, addMethodID, integerValue);
}
env->DeleteLocalRef(listClass);
env->DeleteLocalRef(integerClass);
}
請注意,您不必List在內部創建對象,JNI因為您已經在內部C++代碼中創建了它。它作為native方法的參數傳遞。
您可以在此處找到完整的示例代碼:
https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo046
運行代碼后,您可以看到C++通過List對象傳遞的數據。
> make test
/Library/Java/JavaVirtualMachines/jdk-12.0.1.jdk/Contents/Home/bin/java -Djava.library.path=:./lib -cp target recipeNo046.FillTheList
library: :./lib
1
2
3

TA貢獻2012條經驗 獲得超12個贊
提到的答案似乎適用于 Windows 10,但不適用于 Windows 8。Windows
8 不支持 Cpp 庫中的任何容器。
報告的錯誤將是 - “%1 不是有效的 Win32 應用程序”
,這在運行 Java 程序時發生。
此處生成的 dll 文件似乎是問題所在。
添加回答
舉報