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?