简体   繁体   English

如何从非空终止字符 * 返回 jstring?

[英]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.我在 C++ 中有一个由 char* 和 length 表示的字符串,我想将它作为 jstring 返回给 Java。 NewStringUTF accepts c_style null-terminated strings. NewStringUTF 接受 c_style 以空字符结尾的字符串。 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.我知道我可以将字符串复制到缓冲区并将 '\\0' 附加到末尾,但考虑到性能,我不喜欢复制。

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

How can I implement this method?我怎样才能实现这个方法? (Java version supposed to be 1.8+) (Java 版本应该是 1.8+)

Creating the copy on the C++ side is not only the least effort but also the shortest effort.在 C++ 端创建副本不仅是最少的努力,也是最短的努力。

Here is the best alternative I could come up with:这是我能想到的最佳替代方案:

  1. Use NewByteArray to allocate a Java byte[] of size len使用NewByteArray分配大小为len的 Java byte[]
  2. Fill it with SetByteArrayRegionSetByteArrayRegion填充它
  3. Call String(byte[], CharSet) to decode the bytes from UTF-8.调用String(byte[], CharSet)来解码来自 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.第 2 步和第 3 步都创建了字符串的副本,因此您所做的工作量与问题文本中的工作量相同,只是您调用了 JVM 并分配了额外的对象。

In short: just go with your original plan, there is no simpler or faster solution.简而言之:按照您原来的计划去做,没有更简单或更快的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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