jna coding
C
#include <stdio.h>
int add(int x, int y)
{
return x+y;
}
Java
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
public class JnaTest {
public interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary) Native.loadLibrary((Platform.isWindows() ? "msvcrt" : "c"), CLibrary.class);
void printf(String format, Object... args);
}
public interface MyC extends Library {
int add(int x, int y);
}
public static void main(String[] args) {
CLibrary jnaLib = CLibrary.INSTANCE;
MyC myc = (MyC) Native.loadLibrary("myc", MyC.class);
jnaLib.printf("1+2=%d", myc.add(1, 2));
}
}
build C
mac os x
gcc -dynamiclib -o libmyc.dylib myc.c
export DYLD_LIBRARY_PATH=.
linux
gcc -Wall -fPIC -O2 -c -o libmyc.o myc.c
gcc -shared -o libmyc.so libmyc.o
export LD_LIBRARY_PATH=.
build & run java
jna_jar=/Users/erichan/.m2/repository/com/sun/jna/jna/4.2.2/jna-4.2.2.jar
javac -classpath $jna_jar JnaTest.java
java -classpath $jna_jar:. JnaTest