I have need to pass List of Strings from Java to C through JNI.
My Java program pass a List argument and C program accepts a list.
Below is the code which I tried.
JNIEXPORT jobject JNICALL Java_jni_CallJNIfunction(JNIEnv *env,
jobjectArray jParameters){
list<const char*> cParameters;
jsize stringCount = env->GetArrayLength(jParameters);
for (int i=0; i<stringCount; i++) {
jstring arrElement = (jstring) (env->GetObjectArrayElement(jParameters, i));
const char* nativeElement = env->GetStringUTFChars( arrElement, NULL);
cParameters.push_back(nativeElement);
env->ReleaseStringUTFChars(arrElement, nativeElement);
}
CallCfunction(cParameters);
}
But my JVM crashes at GetStringUTFChars() line.
What is the wrong with this program?
You do:
You release the strings you store into a list, so your list contains a lot of bad pointers!
You must copy the string into a long time allocated space, you have the choice between std::string, char*+malloc, or use-it-and-forget-it approach.
Explanation for the third solution :