开发者

String to JNI gets extra characters

开发者 https://www.devze.com 2023-03-19 11:30 出处:网络
I am calling JNI method from Java app with couple of Str开发者_如何学Cing arguments. I am using env->GetStringChars(arg1, 0 ); to get that strings.

I am calling JNI method from Java app with couple of Str开发者_如何学Cing arguments. I am using env->GetStringChars(arg1, 0 ); to get that strings. Problem is that I sometimes get some extra special characters or string is truncated.


In Java, chars are 16-bit characters (UTF-16 encoded). If you treat them as a plain char* in C you will see nul bytes (which is usually treaded as the end of the String) or other special characters.

Perhaps you should use the UTF encoding which avoid nul char. You will still need to handle special characters which are UTF encoded.

http://java.sun.com/docs/books/jni/html/objtypes.html


Finally I found a solution

const jchar* raw = env->GetStringChars(string, NULL);
if (raw == NULL)
    return NULL;

wchar_t* wsz = new wchar_t[len+1];
memcpy(wsz, raw, len*2);
wsz[len] = 0;

env->ReleaseStringChars(string, raw);

return wsz;
0

精彩评论

暂无评论...
验证码 换一张
取 消