How can I call Java Methods containing String parameter(s) using JNI?

Davanum Srinivas

CallObjectMethod/CallStaticObjectMethod can be used to call Java Methods which need String parameters. Additional JNI functions are needed for converting Java strings to C/C++ strings or the other way around. For example:

char result[256]; 
// Call a java method which returns a string.
jmethodID midToString = env->GetMethodID(cls, "toString", "() Ljava/lang/String;"); 
jstring jstr = (jstring) env->CallObjectMethod(jObj, midToString); 
if (jstr != 0) 
{ 
// Now convert the Java String to C++ char array 
const char* cstr = env->GetStringUTFChars(jstr, 0); 
strcpy(result, cstr); 
env->ReleaseStringUTFChars(jstr, cstr); 
env->DeleteLocalRef(jstr); 
} 

// Convert the C++ char array to Java String 
jstring name = env->NewStringUTF(result); 
// Now use this to call a java method that needs a String parameter.
jmethodID midInitialize = env->GetMethodID (cls, "initialize", "(Ljava/lang/String;)V"); 
env->CallVoidMethod(jObj, midInitialize, name); 
env->DeleteLocalRef(name); 
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact