android jni 字符串的处理
说明:java中使用的是utf-16 c++中使用的utf-8;同时JNI 提供一系列java 和c++之间转换的方法,具体如下。
extern "C" JNIEXPORT jstring JNICALL Java_com_yuanrenxue_course6_14_MainActivity_demoUTFString(JNIEnv *env, jobject thiz) { // TODO: implement demoUTFString() //utf-8 //NewStringUTF utf-8字符串转为java的字符串(java中是utf-16) c中是utf-8 std::string hello = "hello"; jstring str = env->NewStringUTF(hello.c_str()); //获取utf-8之后的字符串 jsize len = env->GetStringLength(str); __android_log_print(6, "yuanrenxue->", "GetStringLength = %d", len); //汉 e6b189(utf-8) u_int8_t c[4] = {0xe6, 0xb1, 0x89, 0x0}; str = env->NewStringUTF(reinterpret_cast<const char *>(c)); len = env->GetStringLength(str); __android_log_print(6, "yuanrenxue->", "GetStringLength(汉) = %d", len); //GetStringUTF Chars jstring -> char * 可能会拷贝 具体看cpu str = env->NewStringUTF(hello.c_str()); const char *r = env->GetStringUTFChars(str, nullptr); for (int i = 0;; i++) { if (r[i] == 0x0) { break; }; __android_log_print(6, "yuanrenxue->", "i = %d,r[i]= %x", i, r[i]); } env->ReleaseStringChars(str, reinterpret_cast<const jchar *>(r)); //GetStringUTFRegion 一定会拷贝 char *buf = static_cast<char *>(malloc(4 * sizeof(char))); env->GetStringUTFRegion(str, 0, 3, buf); for (int i = 0;; i++) { if (buf[i] == 0x0) { break; }; __android_log_print(6, "yuanrenxue->", " i= %x ,buf[i] = %c", i, buf[i]); } free(buf); //env->GetStringChars(); //env->GetStringCritical(); //会暂定gc 造成进程阻塞 //两个都是概率性进行深拷贝, 后者概率更大一些。 return str; }