jni中jString和char*互转

char * Jstring2CStr( JNIEnv * env, jstring jstr ){ char * rtn; jclass clsstring = env->FindClass("java/lang/String"); jstring strencode = env->NewStringUTF("UTF-8"); jmethodID mid = env->GetMethodID(clsstring, "getBytes", "(Ljava/lang/String;)[B"); 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); memcpy(rtn,ba,alen); rtn[alen]=0; } env->ReleaseByteArrayElements(barr,ba,0); return rtn;}jstring strToJstring(JNIEnv* env, const char* pStr){ int strLen = strlen(pStr); jclass jstrObj = env->FindClass("java/lang/String"); jmethodID methodId = env->GetMethodID(jstrObj, "", "([BLjava/lang/String;)V"); jbyteArray byteArray = env->NewByteArray(strLen); jstring encode = env->NewStringUTF("utf-8"); env->SetByteArrayRegion(byteArray, 0, strLen, (jbyte*)pStr); return (jstring) env->NewObject(jstrObj, methodId, byteArray, encode);}

你可能感兴趣的:(jni)