gmuhammad
gmuhammad

Reputation: 1438

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.

Upvotes: 7

Views: 6193

Answers (1)

Tom Whittock
Tom Whittock

Reputation: 4230

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.

Upvotes: 5

Related Questions