c/c++返回中文给java时会乱码,因为java和c/c++的编码格式不一样,java的utf-16,c/c++是utf-8,所以在返回中文字符的时候,包装成gb2312返回。
具体见如下博客链接:
jni交互中文乱问题分析
public class CodeTest {
public native String getChineseFromNative();
public static void main(String[] args) {
// TODO Auto-generated method stub
CodeTest t=new CodeTest();
String result=t.getChineseFromNative();
System.out.println("test=china_code="+result);
}
static {
System.load("D:\\Documents\\Visual Studio 2013\\Projects\\"
+ "JNIChinaCode\\x64\\Debug\\JNIChinaCode.dll");
}
}
#define CRT_SECURE_WARNNING
#include "code_test_CodeTest.h"
#include <string.h>
JNIEXPORT jstring JNICALL Java_code_1test_CodeTest_getChineseFromNative
(JNIEnv *Env, jobject jobj){
//c返回中文字符getJava
char *c_str = "中华人民共和国";
jstring result=(*Env)->NewStringUTF(Env,c_str);
jclass str_class = (*Env)->FindClass(Env, "Ljava/lang/String;");//后面分号
jmethodID constr_mid=(*Env)->GetMethodID(Env,str_class,"<init>","([BLjava/lang/String;)V");
//通过构造函数创建 String 对象,传入byte 和UTF-8 string=new String(byte[] "gb2312");
jbyteArray str_byte=(*Env)->NewByteArray(Env,strlen(c_str));
(*Env)->SetByteArrayRegion(Env,str_byte,0,strlen(c_str),c_str);
jstring utf_set=(*Env)->NewStringUTF(Env,"GB2312");//c/c++传入中文编码成gb2312
return (*Env)->NewObject(Env, str_class, constr_mid, str_byte, utf_set);
};
//运行效果如下图
int compareOrder(int *a, int *b){
return (*a) - (*b);
}
//c排序java数组
JNIEXPORT void JNICALL Java_code_1test_CodeTest_rightOrder
(JNIEnv *Env, jobject jobj, jintArray jarry){
//获取数组指针
jint *arryp= (*Env)->GetIntArrayElements(Env,jarry,NULL);
//获取数组长度
jsize size = (*Env)->GetArrayLength(Env,jarry);
printf("test=length:%d\n",size);
//数组排序
qsort(arryp,size,sizeof(jint),compareOrder);
(*Env)->ReleaseIntArrayElements(Env,jarry,arryp,JNI_COMMIT);
};
java代码和效果图如下