简体   繁体   中英

How to create UTF16 string in JNI for Java from C/C++?

I have a C/C++ char* string which has the smiley but the rest of the content is in ASCII. For eg, Hello World .

When I try to create Java string in JNI using NewStringUTF and NewString the behavior is undefined.

What is the correct way of creating the Java string?

The char* that I had was pointing to true UTF-8 data and not modified UTF-8 data. So, I converted the string to UTF-16 first and then used NewString to generate the Java string. For conversion of UTF-8 to UTF-16 I used this library .

string line = myStringWithSmiley;
u16string utf16line = utf8::utf8to16(line);
return env->NewString((const jchar*)(utf16line.c_str()), utf16line.length());

Try

byte[] bytes = String.valueOf(chars).getBytes(StandardCharsets.UTF_16);
String utf16 = new String(bytes, StandardCharsets.UTF_16);

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