2

I have a JNICALL where I pass a jstring to C++ that needs to be passed to a C++ funciton that gets me a value. Is it possible to call GetStringUTFChars in the return statement. My concern is, that I can not call ReleaseStringUTFChars to free up the memory.

JNIEXPORT jint JNICALL Java_TestClass_getValue(JNIEnv *env, jobject obj, jstring name){
    return t1->getValue(env->GetStringUTFChars(name, 0));
}

It works , but I am not sure If I will get memory leaks or a stackoverflow.

The only other option I see is to do something like that:

JNIEXPORT jint JNICALL Java_TestClass_getValue(JNIEnv *env, jobject obj, jstring name){
    const char* nameChars = env->GetStringUTFChars(name, 0);
    env->ReleaseStringUTFChars(name, nameChars);
    return t1->getValue(nameChars);
}

But that might be even worse. Because according to the JNI documentation ReleaseStringUTFChars

informs the VM that the native code no longer needs access to utf

In my case access to const char* nameChars. But as I need to pass nameChars i would try to access already freed or about to be freed variables.

I would like the first version to be correct. If not, what would you suggest? Is memory from heap allocated even when a variable is not declared?

jteichert
  • 527
  • 1
  • 4
  • 20
  • 2
    How about `auto result = t1->getValue(nameChars); env->ReleaseStringUTFChars(name, nameChars); return result;`? Or write a helper class that gets the data from a `jstring` and releases it when the object falls out of scope. – Michael Apr 09 '15 at 08:31
  • This is what RAII is meant to solve: http://stackoverflow.com/questions/2321511/what-is-meant-by-resource-acquisition-is-initialization-raii – PaulMcKenzie Apr 09 '15 at 08:33
  • RAII can generate code that is safe in either scenario, but the question, I think, is whether `GetStringUTFChars` returns a [local or global reference](http://journals.ecs.soton.ac.uk/java/tutorial/native1.1/implementing/refs.html), or whether that mechanism is even applicable to a `char const*`. I don't think it is, but I'm not entirely certain; the documentation is not very clear on this point. – Wintermute Apr 09 '15 at 08:46
  • _"the question, I think, is whether `GetStringUTFChars` returns a local or global reference"_. Neither AFAIK. `GetStringUTFChars` allocates some memory, copies the strings contents to that memory (doing UTF16 to UTF8 conversion in the process), and returns a pointer to the allocated memory. `ReleaseStringUTFChars` calls `free` on that memory, hence the reason why you need to call `ReleaseStringUTFChars`. – Michael Apr 16 '15 at 12:37

0 Answers0