场景说明
将一个GBK编码的字符串返回给Java层
误区
因为这是一个GBK编码的char*字符串,不可能直接调用函数直接返回:
char* p;
jstring encoding = (env)->NewStringUTF(p);
出现如下的错误:the key point is "Modified UTF-8"is not like "Regular UTF-8", a legal Rgular UTF8 code sequence may beconsidered illegal against Modified UTF8.
正确的方式
需要构建一个GBK编码的jstring,在参数中指定字符串的编码格式
jstring cToJstringutf(JNIEnv* env, char* pat)
{
jclass strClass = (env)->FindClass("java/lang/String");
jmethodID ctorID = (env)->GetMethodID(strClass, "",
"([BLjava/lang/String;)V");
jbyteArray bytes = (env)->NewByteArray(strlen(pat));
(env)->SetByteArrayRegion(bytes, 0, strlen(pat), (jbyte*) pat);
jstring encoding = (env)->NewStringUTF("gb2312");
jstring jstr = (jstring)(env)->NewObject(strClass, ctorID, bytes, encoding);
env->DeleteLocalRef(strClass);
env->DeleteLocalRef(bytes);
env->DeleteLocalRef(encoding);
return jstr;
}
问题编译过程中出现警告:
uses2-byte wchar_t yet the output is to use 4-byte wchar_t;use of wchar_t valuesacross objects may fail
本文转自fengyuzaitu 51CTO博客,原文链接:http://blog.51cto.com/fengyuzaitu/1596484,如需转载请自行联系原作者