当前位置: 技术问答>java相关
如何在VC和JAVA间传递汉字,哪个晓得?
来源: 互联网 发布时间:2015-07-22
本文导语: 如何在VC和JAVA间传递汉字,哪个晓得? | 从Java传入字符到C: Java: name.getBytes(); C/CPP: jsize len; len = env->GetArrayLength(name); jbyte *attrname; attrname = (jbyte *) malloc(sizeof(jbyte)*(len+1)); if ( att...
如何在VC和JAVA间传递汉字,哪个晓得?
|
从Java传入字符到C:
Java:
name.getBytes();
C/CPP:
jsize len;
len = env->GetArrayLength(name);
jbyte *attrname;
attrname = (jbyte *) malloc(sizeof(jbyte)*(len+1));
if ( attrname!= NULL) {
env->GetByteArrayRegion(name, 0, len, attrname);
attrname[len] = '';
}
(char *)attrname就是正确的中文了。
从C传字符到java请使用以下函数:
jstring WindowsTojstring( JNIEnv* env, char* str )
{
jstring rtn = 0;
int slen = strlen(str);
wchar_t* buffer = 0;
if( slen == 0 )
rtn = env->NewStringUTF( str ); //UTF ok since empty string
else
{
int length = MultiByteToWideChar( CP_ACP, 0, (LPCSTR)str, slen, NULL, 0 );
buffer = (wchar_t*)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;
}
Java:
name.getBytes();
C/CPP:
jsize len;
len = env->GetArrayLength(name);
jbyte *attrname;
attrname = (jbyte *) malloc(sizeof(jbyte)*(len+1));
if ( attrname!= NULL) {
env->GetByteArrayRegion(name, 0, len, attrname);
attrname[len] = '';
}
(char *)attrname就是正确的中文了。
从C传字符到java请使用以下函数:
jstring WindowsTojstring( JNIEnv* env, char* str )
{
jstring rtn = 0;
int slen = strlen(str);
wchar_t* buffer = 0;
if( slen == 0 )
rtn = env->NewStringUTF( str ); //UTF ok since empty string
else
{
int length = MultiByteToWideChar( CP_ACP, 0, (LPCSTR)str, slen, NULL, 0 );
buffer = (wchar_t*)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;
}