JNI中string和jstring轉換

傲慢的上校發表於2013-10-10
jstring str2jstring(JNIEnv* env,const char* pat)
{
    //定義java String類 strClass
    jclass strClass = (env)->FindClass("Ljava/lang/String;");
    //獲取String(byte[],String)的構造器,用於將本地byte[]陣列轉換為一個新String
    jmethodID ctorID = (env)->GetMethodID(strClass, "<init>", "([BLjava/lang/String;)V");
    //建立byte陣列
    jbyteArray bytes = (env)->NewByteArray(strlen(pat));
    //將char* 轉換為byte陣列
    (env)->SetByteArrayRegion(bytes, 0, strlen(pat), (jbyte*)pat);
    // 設定String, 儲存語言型別,用於byte陣列轉換至String時的引數
    jstring encoding = (env)->NewStringUTF("GB2312"); 
    //將byte陣列轉換為java String,並輸出
    return (jstring)(env)->NewObject(strClass, ctorID, bytes, encoding);
}
 
 
std::string jstring2str(JNIEnv* env, jstring jstr)
{   
    char*   rtn   =   NULL;   
    jclass   clsstring   =   env->FindClass("java/lang/String");   
    jstring   strencode   =   env->NewStringUTF("GB2312");   
    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);   
    std::string stemp(rtn);
    free(rtn);
    return   stemp;   
} 




// convert jbyteArray to std::string

jsize   alen   =   env->GetArrayLength(rawArray);
	    jbyte*   ba   =   env->GetByteArrayElements(rawArray,JNI_FALSE);
	    if(alen   >   0)
	    {
	        rtn   =   (char*)malloc(alen+1);
	        memcpy(rtn,ba,alen);
	        rtn[alen]=0;
	    }
	    env->ReleaseByteArrayElements(barr,ba,0);
	    std::string theStr(rtn);
	    free(rtn);



// convert jbyteArray to std::string

std:string native_strAddr = env->GetStringUTFChars(strAddr, NULL);

需要include<cstring>和<string>.


相關文章