My app needs to use jni. Logic looks like :
void myJniFunc(JNIEnv *env, jclass clazz, jobjectArray items) {
int count = 10;
struct MyObj *myObjArray = (struct MyObj*)malloc(sizeof(struct MyObj) * count);
for (i = 0; i < count; i++) {
jobject obj = (*env)->GetObjectArrayElement(env, items, i);
jfieldID fieldId = ...;
jstring jstr = (*env)->GetObjectField(env, obj, fieldId);
myObjArray[i].name = (*env)->GetStringUTFChars(env, jstr);
(*env)->DeleteLocalRef(env, obj);
// Location A
}
// some code which will use myObjArray
process(count, myObjectArray);
// Location B
}
And through JNI doc, the array return by GetStringUTFChars should be relased using
(*env)->ReleaseStringUTFChars(env, jstr, myObjArray[i].name);
(*env)->ReleaseLocalRef(env, jstr);
- If I release the returned array at Location A, then myObjArray.name will be empty
- If I release the returned array at Location B, as I will keep the reference of jstring, then "Failed adding to JNI local ref table(has 512 entries)" will happen
My question is : What should I do, if I want to release jstring correctly?
jstring
, or is it supposed to hold a Cchar *
? Seems like it'd be the latter, in which case you should get the characters from each string and copy them into a newly allocatedchar
array, then store those in thedata
field, and then release the Java characters.