原文:http://blog.csdn.net/uper945/article/details/1935706
JNI和C++中的String相互转换
Uper
目前仍在继续先前的工作,这两天一直在折腾jstring 和char* 之间是如何转换的。在网上找了些例子和张孝祥jni的视频,现把自己成功运行例子贴出来。Uper
//jstring to char*
char* jstringTostring(JNIEnv* env, jstring jstr)
{
char* rtn = NULL;
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;
}
//char* to jstring
jstring stoJstring(JNIEnv* env, const char* pat)
{
jclass strClass = env->FindClass("Ljava/lang/String;");
jmethodID ctorID = env->GetMethodID(strClass, "<init>", "([BLjava/lang/String;)V");
jbyteArray bytes = env->NewByteArray(strlen(pat));
env->SetByteArrayRegion(bytes, 0, strlen(pat), (jbyte*)pat);
jstring encoding = env->NewStringUTF("utf-8");
return (jstring)env->NewObject(strClass, ctorID, bytes, encoding);
}
//invoke function
JNIEXPORT jstring JNICALL Java_test_cs_web_SWIFTAlianceCASmfTest_strcal
(JNIEnv *env, jclass obj, jstring jstr1, jstring jstr2)
{
jbyteArray bytes = 0;
jthrowable exc;
char *pszResult = NULL;
char *pszSTR1 = NULL;
char *pszSTR2 = NULL;
pszSTR1 = jstringTostring(env, jstr1);
pszSTR2 = jstringTostring(env, jstr2);
int nlen = sizeof(char)*(strlen(pszSTR1)+strlen(pszSTR2));
pszResult = (char*)malloc(nlen);
strcpy(pszResult, pszSTR1);
strcat(pszResult, pszSTR2);
jstring jstrRe = stoJstring(env, pszResult);
free(pszSTR1);
free(pszSTR2);
free(pszResult);
return(jstrRe);
}
Note: 函数中间有一些签名的定义,不是很好理解。细节请参考sun的jni文档介绍or command javap