问题
I am writing a jna wrapper for a c library, compiled using gcc under cygwin. Depending on how I execute the jna wrapper the java application either just hangs (if executed as unit test under eclipse) or terminates with an Invalid memory exception. The problem seems to occur only the the c library writes something to either stdout or stderr. Here is my minimal (not) working example:
add.c
#include <stdio.h>
int add (int x, int y)
{
fprintf(stdout, "hello world\n" );
return x + y;
}
jna wrapper
public interface Add extends Library
{
Add INSTANCE = (Add) Native.loadLibrary("add", Add.class);
int add(int x, int y);
}
Compiling the c file under cygwin as follows:
gcc -g -Wall -c add.c
gcc -shared -o add.dll add.o
If I remove the fprintf line everything works fine. Both the add.dll and cygwin1.dll are in the java target folder.
回答1:
You are using wrong syntax for fprintf
. It is actually
int fprintf(FILE *restrict stream, const char *restrict format, ...);
You need to pass string format specifier(%s
) too.
来源:https://stackoverflow.com/questions/19272671/jna-invalid-memory-access-when-writing-to-stdout