7

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);
  1. If I release the returned array at Location A, then myObjArray.name will be empty
  2. 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?

2
  • Is the "name" field of MyObj actually supposed to hold a jstring, or is it supposed to hold a C char * ? Seems like it'd be the latter, in which case you should get the characters from each string and copy them into a newly allocated char array, then store those in the data field, and then release the Java characters. Jul 8, 2013 at 4:19
  • @Ernest Friedman-Hill Sorry, I forgot to add line which calls "GetStringUTFChars". I edit the question again. Thanks.
    – cmoaciopm
    Jul 8, 2013 at 5:59

3 Answers 3

7

Since your loop is creating the local ref (GetObjectField), you need to release it (DeleteLocalRef) in the loop, or you'll run up against the limit on local references. You'll have to completely process the Java string between to two calls.

Since you want to keep the bytes of the string for use outside of the loop, you need to copy the bytes because the JVM's pinning (or temporary copy)(GetStringUTFChars) has to be released (ReleaseStringUTFChars) before the string reference is released.

So the sequence for the string inside the loop must be:

  1. GetObjectField
  2. GetStringUTFChars
  3. make your own copy
  4. ReleaseStringUTFChars
  5. DeleteLocalRef

Note: With GetStringUTFChars you are getting a pointer to a modified UTF-8 encoding of the Java String. Two points here:

  1. Your code should be able to handle modified UTF-8 encoded characters. (It has between one and six bytes per character and encodes NUL in a peculiar way.)
  2. The documentation doesn't say if the array is 0-terminated. You can use GetStringUTFLength to get the number of bytes in the modified UTF-8 encoding—not counting any 0-terminator. (Various JNI implementations and The Book do agree that the array is 0-terminated.) If you want to make your own copy with a terminator, be sure to add room for the terminator.

If you'd rather use a UTF-16 encoding, use GetStringChars and GetStringLength. In this case, the array is definitely not terminated; It uses the internal count and string bytes without any conversion.

Or, if you want to change character sets, to say, real "UTF-8", "ASCII", "CP437" or "Windows-1252" or something else your code can handle, use a String.getBytes overload or the Charset class. Use the Charset class if you want control over how to handle characters that are not supported in the target character set.

2
  • MUTF-8 strings are null-terminated.
    – fadden
    Jul 8, 2013 at 20:29
  • @fadden Thanks. I changed the wording a bit to keep it practical. Jul 8, 2013 at 20:57
2

Additionaly to Tom Blodget's post I can add: DO NOT use the DeleteLocalRef method on a jstring object and DO NOT convert the java string from jobject to jstring in the first place (when you retrieve a string from a java method, for instance)! Keep it in the jobject type reference and convert it to jstring only when you pass it as param otherwise you get the "JNI ERROR (app bug): accessed stale Local" error! For instance, don't do such thing:

jstring imeiObj = (jstring)env->CallObjectMethod(telephonyManagerObj, jniInfo->jniCache.telephonyManagerClass_getDeviceIdMethod, i);
const char* imeiStr = env->GetStringUTFChars(imeiObj, &isCopy);
env->DeleteLocalRef((jobject)imeiObj);

Better do:

jobject imeiObj = env->CallObjectMethod(telephonyManagerObj, jniInfo->jniCache.telephonyManagerClass_getDeviceIdMethod, i);
const char* imeiStr = env->GetStringUTFChars((jstring)imeiObj, &isCopy);
env->DeleteLocalRef(imeiObj);

I have no idea why it is so

0

After some experiments, I get an answer, but I am not sure whether it is exactly correct. I delete the reference of jstring in the loop, error "Failed adding to JNI local ref table(has 512 entries)" does not happen any more.

void myJniFunc(JNIEnv *env, jclass clazz, jobjectArray items) {
    int count = 10;
    jstring tempArray[count];
    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
        tempArray[i] = jstr;
        (*env)->DeleteLocalRef(jstr);
    }

    // some code which will use myObjArray
    process(count, myObjectArray);

    // Location B
    for (i = 0; i < count; i++) {
        (*env)->ReleaseStringUTFChars(env, tempArray[i], myObjectArray[i].name);
    }
}

My concern is : The 2nd parameter of function "ReleaseStringUTFChars" needs to be a jstring. So I create an array to hold reference of jstring for later release. As I delete the reference of jstring in the loop, which means jstring is freed. Is there any problem I call "ReleaseStringUTFChars" over that jstring here? Through my test, I have not encountered any problem.

2
  • 1
    It's probably what would be called "undefined behavior." The local reference to the string has been released but the string is still pinned (or has memory allocated for a copy), and then another operation is performed with the local reference. Jul 8, 2013 at 14:49
  • 2
    Don't use a local reference after deleting it. I'd expect CheckJNI mode to reject the call. The current implementation doesn't use the jstring reference in the Release call, but that could change.
    – fadden
    Jul 8, 2013 at 20:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.