Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert vector to jobject in C++/JNI?

I am using Java native function -

public native ArrayList<String> parseXML();

In C++ my native function -

vector<string> resultList;

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

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

like image 416
anirudha mundada Avatar asked Oct 15 '11 08:10

anirudha mundada


2 Answers

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; 

for further information see:

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

like image 138
Dyonisos Avatar answered Oct 26 '22 13:10

Dyonisos


The method is:

bool add(Object);

So the signature is:

"(Ljava/lang/Object;)Z"

More at: 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; 
like image 28
qwertzui11 Avatar answered Oct 26 '22 13:10

qwertzui11