-1

I am learning to use C++ in Android.

The following function works well, but I do not know how to use ReleaseStringUTFChars(fileName, 0) to release (or free) the memory allocated by env->GetStringUTFChars(input, 0);

Activity_stringFromJNI(
        JNIEnv *env,
        jobject, /* this */
        jstring input) {
    const char *str_C = env->GetStringUTFChars(input, 0);
    char *data = funcX(str_C); // funcX allocates with malloc

    // env->ReleaseStringUTFChars(input, str_C); ???

    free(data); // Freeing funcX allocations
    return env->NewStringUTF(someString.c_str());
}

Also, I have been trying to see the documentation, but I can't find it. How can I check if the memory is being released or freed correctly? Thanks!

1 Answers1

3

Per the JNI documentation (which is available on Oracle's website, the owner of Java), you simply need to pass to ReleaseStringUTFChars() the original jstring and the const char * pointer that GetStringUTFChars() returned, eg:

Activity_stringFromJNI(
        JNIEnv *env,
        jobject, /* this */
        jstring input)
{
    const char *str_C = env->GetStringUTFChars(input, 0);
    char *data = funcX(str_C); // funcX allocates with malloc
    env->ReleaseStringUTFChars(input, str_C);

    // ... data is being used ...
    // ... data is being used ...

    free(data); // Freeing funcX allocations
    return env->NewStringUTF(someString.c_str());
}

On a side note, note that JNI deals with Modified UTF-8, not standard UTF-8. But most C++ code that deals with UTF-8 is likely to deal with standard UTF-8, not Modified UTF-8. So, it is generally better to deal with Java strings in their native UTF-16 encoding rather than UTF-8, if you can help it (GetStringChars(), ReleaseStringChars(), NewString(), etc).

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770