在C ++ / JNI中将vector转换为jobject?

时间:2011-10-15 08:52:01

标签: java c++ java-native-interface

我正在使用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类型?

2 个答案:

答案 0 :(得分:13)

您必须在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

答案 1 :(得分:7)

方法是:

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;