使用类似下面的函数转化,
jstring CharTojstring(JNIEnv* env, char* str) {
jstring rtn = 0;
jsize len = strlen(str);
jclass clsstring = env->FindClass("java/lang/String");
//new encode string default "GBK"
jstring strencode = env->NewStringUTF(CURRENT_ENCODE);
jmethodID mid = env->GetMethodID(clsstring, "<init>", "([BLjava/lang/String
V");
jbyteArray barr = env->NewByteArray(len);
env->SetByteArrayRegion(barr,0,len,(jbyte*)str);
//call new String(byte[] b,String encode)
rtn = (jstring)env->NewObject(clsstring,mid,barr,strencode);
return rtn;
}
char* jstringToChar(JNIEnv* env, jstring jstr) {
char* rtn = NULL;
jclass clsstring = env->FindClass("java/lang/String");
//new encode string default "GBK"
jstring strencode = env->NewStringUTF(CURRENT_ENCODE);
jmethodID mid = env->GetMethodID(clsstring, "getBytes", "(Ljava/lang/String
[B");
//call String.getBytes method to avoid incompatible migrating into solaris
jbyteArray barr= (jbyteArray)env->CallObjectMethod(jstr,mid,strencode);
jsize alen = env->GetArrayLength(barr);
jbyte* ba = env->GetByteArrayElements(barr,JNI_FALSE);
if(alen > 0) {
rtn = (char*)malloc(alen+1);
//new char[alen+1];
memcpy(rtn,ba,alen);
rtn[alen]=0;
}
env->ReleaseByteArrayElements(barr,ba,0);
return rtn;
}