我正在为 c 库编写一个 jna 包装器,在 cygwin 下使用 gcc 编译。根据我执行 jna 包装器的方式,java 应用程序要么挂起(如果在 eclipse 下作为单元测试执行),要么以无效内存异常终止。问题似乎只发生在 c 库向 stdout 或 stderr 写入内容时。 这是我最小的(不是)工作示例:
添加.c
#include <stdio.h>
int add (int x, int y)
{
fprintf(stdout, "hello world\n" );
return x + y;
}
jna 包装器
public interface Add extends Library
{
Add INSTANCE = (Add) Native.loadLibrary("add", Add.class);
int add(int x, int y);
}
在cygwin下编译c文件如下:
gcc -g -Wall -c add.c
gcc -shared -o add.dll add.o
如果我删除 fprintf 行,一切正常。 add.dll 和 cygwin1.dll 都在 java 目标文件夹中。
最佳答案
您对 fprintf
使用了错误的语法。其实是
int fprintf(FILE *restrict stream, const char *restrict format, ...);
您还需要传递字符串格式说明符(%s
)。
关于c - JNA 写入 stdout 时内存访问无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19272671/