JNA中字节数组中的垃圾值



我正在编写一个示例C程序,只是为了打印使用JNA从Java传递给程序的输入参数。C程序必须接受unsigned char *作为输入。我的C程序像

void foo(unsigned char * inp){
setbuf(stdout, NULL);
printf("data received is %sn",inp);
printf("The size is %d n",strlen(inp));
}

Java我正在使用字节数组

调用函数
/* load library*/
libPGM=loadLibrary(); // user defined function to load C library

String str = "Abcdefg";
byte[] byteArr = str.getBytes();
System.out.println("byte length is :"+byteArr.length);
String str_2=new String(byteArr);
System.out.println("Inside the java pgm "+str_2);
libPGM.foo(byteArr);

这是我得到的输出

[stdout] (default task-1) byte length is :7
[stdout] (default task-1) Inside the java pgm Abcdefg
data received is Abcdefg?�$��
The size is 12 

我不明白为什么会发生这种事。为什么我看到垃圾值,为什么长度增加了??

如果我传递一个字符串而不是字节数组,它工作得很好,但在原始的C程序中,字符串需要覆盖,因此我不能传递字符串参数作为输入。如有任何帮助,不胜感激。

您的本机代码假设该数组是一个以空结尾的字符串。但是Java不会空终止字符串。并且字节数组不能以空结束,因为0字节是一个有效值。

最新更新