Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert char[] to jstring in JNI ?

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 ?

like image 577
David Guo Avatar asked Jan 10 '12 02:01

David Guo


2 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);
like image 166
David Guo Avatar answered Oct 24 '22 00:10

David Guo


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

char *returnString = (char*)malloc(10);
strcpy(returnString, "电脑");
return  (*jnienv)->NewStringUTF(jnienv, returnString);
like image 40
tartaruga_casco_mole Avatar answered Oct 24 '22 00:10

tartaruga_casco_mole