首页 > 其他 > 详细

JAVA 通过 JNA 调用 C程序 dll 函数传入中文参数问题

时间:2014-02-19 22:34:23      阅读:606      评论:0      收藏:0      [点我收藏+]

    JAN目前是Java调用C或C++遗留程序dll函数的一种流行方式,方便快捷。其Java和C之间的数据类型对应方式如下:

Java Type

C Type

Native Representation

boolean

int

32-bit integer (customizable)

byte

char

8-bit integer

char

wchar_t

platform-dependent

short

short

16-bit integer

int

int

32-bit integer

long

long long, __int64

64-bit integer

float

float

32-bit floating point

double

double

64-bit floating point

Buffer
Pointer

pointer

platform-dependent (32- or 64-bit pointer to memory)

<T>[] (array of primitive type)

pointer
array

32- or 64-bit pointer to memory (argument/return)
contiguous memory (struct member)

除了上面的类型,JNA还支持常见的数据类型的映射。

String

char*

NUL-terminated array (native encoding orjna.encoding)

WString

wchar_t*

NUL-terminated array (unicode)

String[]

char**

NULL-terminated array of C strings

WString[]

wchar_t**

NULL-terminated array of wide C strings

Structure

struct*
struct

pointer to struct (argument or return) (or explicitly)
struct by value (member of struct) (
or explicitly
)

Union

union

same as Structure

Structure[]

struct[]

array of structs, contiguous in memory

Callback

<T> (*fp)()

function pointer (Java or native)

NativeMapped

varies

depends on definition

NativeLong

long

platform-dependent (32- or 64-bit integer)

 
    
    多数情况下,Java与C间的字符串传入,都是通过Java的String传入到C中的char*,但是由于Java IDE编码问题和JNA的不完善,如果传入的是中文字符,则C中函数会接收不正确。

    一种解决方发是,将Java IDE的编码格式设置成GBK,之后将String转化成byte[]传入C中,当然,在Java的JNA函数声明时,C函数的参数类型直接替换成byte[]即可,C程序中的原始函数参数依然保持char*,实例代码如下:

public interface TEST extends Library {         
	TEST INSTANCE = (TEST)Native.loadLibrary("tcchost", TEST.class);		
	public int cfun(int filenamelen, byte[] filename); }	}
static public int JavaFun(String filename){
		int res = -1;
		try{			
			byte[] midbytes = filename.getBytes("gbk");
			res =  TEST.INSTANCE.cfun(midbytes.length,midbytes);
		}
		catch(IOException e){	
		}
		return res;	
	}



JAVA 通过 JNA 调用 C程序 dll 函数传入中文参数问题

原文:http://blog.csdn.net/trustbo/article/details/19479031

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!