在C++/JNI中将向量转换为作业?

2022-09-02 13:12:26

我正在使用Java原生函数 -

public native ArrayList<String> parseXML();

C++我的原生函数 -

vector<string> resultList;

JNIEXPORT jobject JNICALL Java_Sample1_parseXML
(JNIEnv *env, jobject obj){
   // logic
   return resultList;   // here getting error
}

我的问题是如何将resultList(向量类型)转换为jobject类型?


答案 1

您必须在C++中为 ArrayList 创建一个包装器。像这样:

vector <char*> vec;

jclass clazz = (*env).FindClass("java/util/ArrayList");
jobject obj = (*env).NewObject(clazz, (*env).GetMethodID(clazz, "<init>", "()V"));

for (int n=0;n<vec.size();n++)
{
   char* str = (char*) static_cast<char*>(vec[n]);

   jstring _str = (*env).NewStringUTF(str);

   (*env).CallVoidMethod(object, (*env).GetMethodID(clazz, "add", "(java/lang/Object)V"), _str);

}

return obj; 

有关更多信息,请参阅:

http://download.oracle.com/javase/1.4.2/docs/guide/jni/spec/functions.html


答案 2

方法是:

bool add(Object);

所以签名是:

"(Ljava/lang/Object;)Z"

更多: http://docs.oracle.com/javase/1.5.0/docs/guide/jni/spec/types.html#wp276

vector <char*> vec;

jclass clazz = (*env).FindClass("java/util/ArrayList");
jobject obj = (*env).NewObject(clazz, (*env).GetMethodID(clazz, "<init>", "()V"));
for (int n=0;n<vec.size();n++)
{
    char* str = (char*) static_cast<char*>(vec[n]);
    jstring _str = (*env).NewStringUTF(str);
    (*env).CallBooleanMethod(object, (*env).GetMethodID(clazz, "add", "(Ljava/lang/Object;)Z"), _str);
}
return obj; 

推荐