Home » Android » android – how to convert char[] to jstring in JNI ?

android – how to convert char[] to jstring in JNI ?

Posted by: admin June 15, 2020 Leave a comment

Questions:

In jni, I want convert the char * to jstring using following method:

env->NewStringUTF(chm_pcText)

it works for english text, but failed with Chinese, and get following message:

JNI WARNING: illegal continuation byte.

How to solve it ?

How to&Answers:

I just solve it:
two steps, first: convert the char * to jbyteArray, then call java String’s contructor to generate a jstring.

 strClass = global_env->FindClass("java/lang/String"); 
 ctorID = global_env->GetMethodID(strClass, "<init>", "([BLjava/lang/String;)V"); 
 encoding = global_env->NewStringUTF("GBK"); 

jbyteArray bytes = global_env->NewByteArray(strlen(chm_pcText)); 
global_env->SetByteArrayRegion(bytes, 0, strlen(chm_pcText), (jbyte*)chm_pcText); 
jstring str = (jstring)global_env->NewObject(strClass, ctorID, bytes, encoding);

Answer:

NewStringUTF worked for me. Here is code that worked for me:

char *returnString = (char*)malloc(10);
strcpy(returnString, "电脑");
return  (*jnienv)->NewStringUTF(jnienv, returnString);