转载请注明出处:http://blog.csdn.net/l1028386804/article/details/47002207

1、将java字符串转化为c++字符串

/**
 *工具方法
 *将java字符串转化为c++字符串
 *返回字符串数组的首地址
 */
char* Jstring2CPPStr(JNIEnv* env, jstring jstr, jstring encode) {
	char* rtn = NULL;
	jclass clsstring = env->FindClass("java/lang/String");
	jstring strencode = env->NewStringUTF(encode);
	jmethodID mid = env->GetMethodID(clsstring, "getBytes","(Ljava/lang/String;)[B");
	jbyteArray barr = (jbyteArray)env->CallObjectMethod(jstr, mid,strencode); // String .getByte("GB2312");
	jsize alen = env->GetArrayLength(barr);
	jbyte* ba = env->GetByteArrayElements(barr, JNI_FALSE);
	if (alen > 0) {
		rtn = (char*) malloc(alen + 1); //"\0"
		memcpy(rtn, ba, alen);
		rtn[alen] = 0;
	}
	env->ReleaseByteArrayElements(barr, ba, 0); //
	return rtn;
}

2、将java字符串转化为c字符串

/**
 *工具方法
 *将java字符串转化为c字符串
 *返回字符串数组的首地址
 */
char* Jstring2CStr(JNIEnv* env, jstring jstr, jstring encode) {
	char* rtn = NULL;
	jclass clsstring = (*env)->FindClass(env, "java/lang/String");
	jstring strencode = (*env)->NewStringUTF(env, encode);
	jmethodID mid = (*env)->GetMethodID(env, clsstring, "getBytes","(Ljava/lang/String;)[B");
	jbyteArray barr = (jbyteArray)(*env)->CallObjectMethod(env, jstr, mid,strencode); // String .getByte("GB2312");
	jsize alen = (*env)->GetArrayLength(env, barr);
	jbyte* ba = (*env)->GetByteArrayElements(env, barr, JNI_FALSE);
	if (alen > 0) {
		rtn = (char*) malloc(alen + 1); //"\0"
		memcpy(rtn, ba, alen);
		rtn[alen] = 0;
	}
	(*env)->ReleaseByteArrayElements(env, barr, ba, 0); //
	return rtn;
}
温馨提示:大家可以到链接http://download.csdn.net/detail/l1028386804/8922611获取完整的JNI调用示例代码