简体   繁体   中英

How to return jstring from non null-terminated char*?

I have a string represented by char* and length in c++, and I want to return it to Java as a jstring. NewStringUTF accepts c_style null-terminated strings. I know i can copy my string to a buffer and append '\\0' to the end, but in consideration of performance, I don't prefer the copy.

jstring convert(char* dest, size_t len) {
 ???
}

How can I implement this method? (Java version supposed to be 1.8+)

Creating the copy on the C++ side is not only the least effort but also the shortest effort.

Here is the best alternative I could come up with:

  1. Use NewByteArray to allocate a Java byte[] of size len
  2. Fill it with SetByteArrayRegion
  3. Call String(byte[], CharSet) to decode the bytes from UTF-8.

Both step 2 and step 3 create a copy of the string, so you're doing the same amount of work as in your question text, except you're also calling into the JVM and allocating extra objects.

In short: just go with your original plan, there is no simpler or faster solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM