jni java 中文乱码_Windows环境下JNI中Jstring中文乱码解决方案 | 学步园

Java code

package zeph.example;

import java.io.IOException;

public class JstringExample {

/**

* @param Jstring For Chinese

* @author Ben Zeph

*/

public native String stringMethod(String text);

public static void main(String[] args) throws IOException{

// TODO Auto-generated method stub

JstringExample Je = new JstringExample();

System.loadLibrary("example");

String str = "天灵灵,地灵灵,乱码乱码,消失吧!!!";

System.out.println("the String in java is " + '"' + str + '"');

System.out.println("the String return by C is "+Je.stringMethod(str));

}

}

C code example_h.h

#include "jni.h"

#ifndef _Included_example_h

#define _Included_example_h

#ifdef __cplusplus

extern "C" {

#endif

JNIEXPORT jstring JNICALL Java_zeph_example_JstringExample_stringMethod(JNIEnv *, jobject, jstring);

/*Java: stringMethod

*Fuction: tranform a java string to c char*

*Author: Ben Zeph

*/

#ifdef __cplusplus

}

#endif

#endif

C code exampledll.cpp

#include "example_h.h"

#include "jni.h"

#include

#include

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, const 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;

}

JNIEXPORT jstring JNICALL Java_zeph_example_JstringExample_stringMethod(JNIEnv *env, jobject obj, jstring string)

{

const char *str ;

jstring tostring;

str = jstringToWindows(env, string);

printf("The string in C code %s/n",str);

tostring = WindowsTojstring(env,str);

return tostring;

}

void main(){}

C中的两个函数

char* jstringToWindows( JNIEnv *env, jstring jstr )

jstring WindowsTojstring( JNIEnv *env, const char* str )

转载于其他文章,在此感谢其作者

代码中需要的两个头文件jni.h和jni_md.h

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值