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

2022-01-25 00:00:00 c++ java java-native-interface

我正在使用 Java 原生函数 -

I am using Java native function -

public native ArrayList<String> parseXML();

在 C++ 中我的原生函数 -

In C++ my native function -

vector<string> resultList;

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

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

My problem is that how to convert resultList (vector type) to jobject type?

推荐答案

您必须在 C++ 中为 ArrayList 创建一个包装器.比如:

You would have to create a wrapper for the ArrayList in C++. Something like:

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

相关文章