std::string hello = "Hello from C++"; jstring jHello=env->NewStringUTF(hello.c_str()); 复制代码
jstring util_char_to_jstring(JNIEnv *env, const char *pat) { //定义java String类 strClass jclass strClass = (env)->FindClass("java/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("utf-8"); //将byte数组转换为java String,并输出 return (jstring) (env)->NewObject(strClass, ctorID, bytes, encoding); } 复制代码
void util_jstring_to_char(JNIEnv *env, jstring jstr, char *result) { if (env == NULL || jstr == NULL) { return; } 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) { memcpy(result, ba, alen); result[alen] = 0; } env->ReleaseByteArrayElements(barr, ba, 0); } 复制代码
而 char*
是可以直接赋值给 string
的:
string s; char *p = "hello";//直接赋值 s = p; 复制代码
string util_int_to_string(unsigned int n) { string sResult; stringstream ssTmp; ssTmp << n; ssTmp >> sResult; return sResult; } 复制代码
char *convertJByteArrayToChar(JNIEnv *env, jbyteArray byYUV1_) { jbyte *bytes = env->GetByteArrayElements(byYUV1_, 0); int arrayLength = env->GetArrayLength(byYUV1_); char *chars = new char[arrayLength + 1]; memset(chars, 0x0, arrayLength + 1); memcpy(chars, bytes, arrayLength); chars[arrayLength] = 0; env->ReleaseByteArrayElements(byYUV1_, bytes, 0); return chars; } 复制代码
jbyteArray util_char_to_jbyteArray(JNIEnv *env, char *data, int length) { jbyte *by = (jbyte *) data; jbyteArray jarray = env->NewByteArray(length); env->SetByteArrayRegion(jarray, 0, length, by); return jarray; } 复制代码