/*******************************************************************
*char*----->jstring
*******************************************************************/
jstring c2js(JNIEnv* env, const char* pat)
{
jclass strClass = env->FindClass("java/lang/String");
jmethodID ctorID = env->GetMethodID(strClass, "", "([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);
}
/******************************************************************
*jstring ----->char*
********************************************************************/
char* js2c(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;
}
/*****************************************************************
*wchar_t* ----->jstring
*******************************************************************/
jstring js2w(JNIEnv* env, wchar_t* str)
{
size_t len = wcslen(str);
jchar* str2 = (jchar*)malloc(sizeof(jchar)*(len+1));
int i;
for (i = 0; i < len; i++)
str2[i] = str[i];
str2[len] = 0;
jstring js = env->NewString(str2, len);
free(str2);
return js;
}
/******************************************************************
*jstring----->wchar_t*
********************************************************************/
wchar_t* w2js(JNIEnv* env, jstring str)
{
int len = env->GetStringLength(str);
wchar_t *w_buffer = new wchar_t[len];
memset(w_buffer,0,len+1);
w_buffer[len]='\0';
wcsncpy(w_buffer,(wchar_t *)env->GetStringChars(str,0),len);
env->ReleaseStringChars(str,(const unsigned short *)w_buffer);
return w_buffer;
}
阅读(5419) | 评论(0) | 转发(0) |