Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Must ReleaseStringUTFChars be called after GetStringUTFChars (when passing the char* to C function)?

I am a bit confused about the the objects which is passed to c from java? Should they be deleted inside the native jni method or they will be garbage collected when the method returns. For example:

if I have a native declaration in my java file public native printString(String msg); and the native method is using const char *message = (jni_env)->GetStringUTFChars(msg, &iscopy); to get c-style character array of string. Shoud I call (jni_env)->ReleaseStringUTFChars(msg, message); after doing all the stuff in native method. If yes, then why it is necessary? Why not java runtime environment be doing this on the behalf of programmer? After all the string was declared and passed from java environment.

like image 997
gmuhammad Avatar asked Aug 21 '12 17:08

gmuhammad


1 Answers

The Get Characters function pins the characters in memory until the Release method is called. Java is unable to garbage collect or otherwise move this data until it is sure that no-one is using it.

The Java VM can not know anything about how long the memory will be used for once it leaves the Java virtual machine, therefore it requires manual notification that the memory has been finished with.

like image 129
Tom Whittock Avatar answered Oct 19 '22 17:10

Tom Whittock