jstring(JNI) to std::string(c++) with utf8 characters(带有 utf8 字符的 jstring(JNI) 到 std::string(c++))
问题描述
如何将 jstring
(JNI) 转换为 std::string
(c++) 与 utf8
字符?
How to convert jstring
(JNI) to std::string
(c++) with utf8
characters?
这是我的代码.它适用于非 utf8 字符,但适用于 utf8 字符.
this is my code. it worked with non-utf8 characters, but it is wrong with utf8 characters.
推荐答案
经过很长时间才找到解决方案.我找到了一条路:
After a lot time to find solution. i was found a way:
在 java 中,unicode char 将使用 2 个字节 (utf16
) 进行编码.所以 jstring
将包含字符 utf16
.c++ 中的 std::string
本质上是一个字节串,而不是字符,所以如果我们想将 jstring
从 JNI
传递到 c++
,我们已经将 utf16
转换为字节.
In java, a unicode char will be encoded using 2 bytes (utf16
). so jstring
will container characters utf16
. std::string
in c++ is essentially a string of bytes, not characters, so if we want to pass jstring
from JNI
to c++
, we have convert utf16
to bytes.
在文档中 JNI 函数,我们有 2 个函数从 jstring 中获取字符串:
in document JNI functions, we have 2 functions to get string from jstring:
GetStringUTFChars
,它将返回一个修改后的utf8.
GetStringChars
将返回 jbyte *,我们将从 jbytes 中读取 char 代码并在 c++ 中将其转换为 char
GetStringChars
will return jbyte *, we will read char code from jbytes and convert it to char in c++
这是我的解决方案(适用于 ascii
和 utf8
字符):
this is my solution (worked well with ascii
and utf8
characters):
这篇关于带有 utf8 字符的 jstring(JNI) 到 std::string(c++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!