19

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?

1
  • 2
    +1: It a lot harder than you might imagine. ;) Commented Oct 15, 2011 at 9:12

2 Answers 2

15

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

Sign up to request clarification or add additional context in comments.

5 Comments

Nice answer. But it would be absolutely great, if someone writes an adapter for STL vector that implements java.util.List. Quite fascinating exercise!
Right! This would be the solution of the solutions.
Pardon my pedantry, but isn't (char*)static_cast<char*> redundant?
By the way, in CallVoidMethod, what is tha object parameter exactly? I mean as I found out, that should be a jobject. If I try to do the same as above, the compiler says, that object isn't declared in the scope.
what is the "object" in CallVoidMethod() and where are we using "jobject obj " declared at the top of code?
9

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; 

4 Comments

This looks like an almost character-by-character copy of the first answer.
@moshbear: it's not. CallBooleanMethod here, CallVoidMethod there. The rest is rather mechanical, so similarities are expected.
Fair enough. My comment on the previous answer w.r.t. (char*)static_cast<char*> being redundant still stands, though.
what is the "object" in CallVoidMethod() and where are we using "jobject obj " declared at the top of code?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.