jni string转换测试

成功一:
#include "cyper_jni_Test.h"
#include <windows.h>

/*
 * Class:     cyper_jni_Test
 * Method:    getString
 * Signature: ()Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_cyper_jni_Test_getString
(JNIEnv * env, jobject obj){
	const wchar_t* str = L"Here is a quite long and useless string. Note that this even works with non-ASCII characters, like in中文";
	size_t len = wcslen(str);
	if (sizeof(wchar_t) != sizeof(jchar)) {
		printf("this is linux\n");
		// In Linux, we get there.
		// First, allocate a buffer for the string to pass to Java, not forgetting the \0
		jchar* str2 = (jchar*)malloc((len+1)*sizeof(jchar));
		int i;
		for (i = 0; i < len; i++)
			// This discards two bytes in str[i], but these should be 0 in UTF-16
			str2[i] = str[i];
		str2[len] = 0;
		// Now we have a compatible string!
		jstring js = env->NewString(str2, len);
		// And we can free the buffer, to prevent memory leaks
		free(str2);
		return js;
	} 
	else
	{
		printf("this is windows\n");
		// Under Windows, we don't need such a hack
		return env->NewString((const jchar *)str, len);
	}
}

参考:http://yaojingguo.iteye.com/blog/542383

成功二:

//version 2
std::wstring wstr(L"hello开源中国");
//NewString的第一个参数是unicode版本的jchar *, 所以要把wstring转成wchar_t *
const wchar_t * pwchar = const_cast<wchar_t*>(wstr.c_str());
return env->NewString((const jchar *)pwchar,wcslen(pwchar));

参考: http://www.linuxidc.com/Linux/2012-05/60870.htm


成功三:

。。。

你可能感兴趣的:(String,jni)