// JNIDemo.cpp : 定义 DLL 应用程序的导出函数。
//
#include "stdafx.h"
#include "jni_demo_str_DemoStr.h"
#include <iostream>
#include <windows.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
using namespace std;
char* jstringToWindows( JNIEnv *env, jstring jstr );
jstring WindowsTojstring( JNIEnv* env, char* str ) ;
JNIEXPORT jstring JNICALL Java_jni_demo_str_DemoStr_getPath
(JNIEnv *env, jobject obj, jstring recv_buf){
char * Buf_Return;
Buf_Return = (char*)malloc(1024);
const char * recvtest = jstringToWindows( env, recv_buf );
/*上句recvtest接收Java传过来的中文字符串正确,如果改为下句,则出现乱码:
const char * recvtest = (*env)->GetStringUTFChars( env,recv_buf,0);
*/
printf( " c recv :[%s]\n" , recvtest);
sprintf(Buf_Return,"接收中文chinese!");
printf( "\n\n\n c send :[%s]\n" , Buf_Return);
recv_buf = WindowsTojstring(env ,Buf_Return);
/*上句recv_buf传windows本地C中含有中文字符串给Java正确;如果改为下句出现乱码:
recv_buf = (*env)->NewStringUTF( env, Buf_Return );
*/
return recv_buf;
}
char* jstringToWindows( JNIEnv *env, jstring jstr )
{
int length = (env)->GetStringLength(jstr );
const jchar* jcstr = (env)->GetStringChars(jstr, 0 );
char* rtn = (char*)malloc( length*2+1 );
int size = 0;
size = WideCharToMultiByte( CP_ACP, 0, (LPCWSTR)jcstr, length, rtn,(length*2+1), NULL, NULL );
if( size <= 0 )
return NULL;
(env)->ReleaseStringChars(jstr, jcstr );
rtn[size] = 0;
return rtn;
}
jstring WindowsTojstring( JNIEnv* env, char* str )
{
jstring rtn = 0;
int slen = strlen(str);
unsigned short * buffer = 0;
if( slen == 0 )
rtn = (env)->NewStringUTF(str );
else
{
int length = MultiByteToWideChar( CP_ACP, 0, (LPCSTR)str, slen, NULL, 0 );
buffer = (unsigned short *)malloc( length*2 + 1 );
if( MultiByteToWideChar( CP_ACP, 0, (LPCSTR)str, slen, (LPWSTR)buffer, length ) >0 )
rtn = (env)->NewString( (jchar*)buffer, length );
}
if( buffer )
free( buffer );
return rtn;
}
来自: https://ironurbane.iteye.com/blog/425513
未经允许不得转载:Dram乘风博客 » javaJNI 交互中文乱码处理
来自X市的用户(2019-01-06)
评论暂不开放 ...