keelar
keelar

Reputation: 6026

GetStringUTFChars and its string copy behavior

In the JNI document, GetStringUTFChars(), which converts a java string jstring to c++ const char*, will return an optional jboolean flag indicating whether it performs copy or not within the function call. However, the document does not mention when GetStringUTFChars() will or will not perform copy. My questions are:

  1. Under which condition GetStringUTFChars() will perform a copy?
  2. Is there any way to avoid copy in GetStringUTFChars()?
  3. If the answer to question 2. is true, is it suggested to avoid such copy?

Upvotes: 1

Views: 2044

Answers (2)

marcprux
marcprux

Reputation: 10385

It will always be up to the JVM implementation whether to copy the string or not, but you can reduce the likelihood of a copy being made by instead using GetStringCritical instead of GetStringUTFChars. But do note that GetStringCritical returns a UTF-16-encoded string (as opposed to the UTF-8 encoded string returned by GetStringUTFChars), so you may need to do a conversion into your desired encoding.

In my experience (Oracle 1.8.0_51-b16 on OS 10.11), GetStringUTFChars always returns a copy and GetStringCritical never returns a copy, which isn't surprising since Java stores Strings internally as UTF-16, and so extracting UTF-8 will probably require making a copy of the data.

See: https://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/functions.html#GetStringCritical_ReleaseStringCritical

Upvotes: 3

PaulMcKenzie
PaulMcKenzie

Reputation: 35455

According to the book "Essential JNI Java Native Interface", it is the implementation of the JVM that decides whether a copy is done or not. So no, you have no control over the copying.

Upvotes: 3

Related Questions