skboro
skboro

Reputation: 195

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?

Upvotes: 0

Views: 1465

Answers (1)

skboro
skboro

Reputation: 195

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());

Upvotes: 2

Related Questions