当前位置: 代码迷 >> JavaScript >> jstring, String, char* 转换函数【转】
  详细解决方案

jstring, String, char* 转换函数【转】

热度:522   发布时间:2013-03-06 16:20:31.0
jstring, String, char* 变换函数【转】

#include <malloc.h>
#include <string.h>
#include <stdlib.h>
#include <vcclr.h>

using namespace System;
using namespace System::Text;

// jstring To String
String^ jstringToStr(JNIEnv* env, jstring jstr)
{
??? char* str = jstringTostring(env, jstr);
??? String^ value = gcnew String(str);
??? free(str);
??? return value;
}

// 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;
}

// String To jstring
jstring strTojstring(JNIEnv* env, String^ rtn)
{
??? pin_ptr<const wchar_t> wch = PtrToStringChars(rtn);
??? size_t convertedChars = 0;
??? size_t sizeInBytes = ((rtn->Length + 1) * 2);
??? char *ch = (char *)malloc(sizeInBytes);
??? errno_t err = wcstombs_s(&convertedChars,
??? ??? ch, sizeInBytes,
??? ??? wch, sizeInBytes);
??? jstring js = stringTojstring(env, ch);
??? free(ch);
??? return js;
}

// char* To jstring
jstring stringTojstring(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);
}

?

?

?
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;??
}??

?

?

?

转自:http://dncsoft.iteye.com/blog/1010213

?????????? http://www.cnblogs.com/lichien/archive/2011/10/11/2206828.html

  相关解决方案