Skip to content

Instantly share code, notes, and snippets.

@feuyeux
Last active September 8, 2016 10:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save feuyeux/7a5bf801b25abe205c26bcf4dc925e8c to your computer and use it in GitHub Desktop.
Save feuyeux/7a5bf801b25abe205c26bcf4dc925e8c to your computer and use it in GitHub Desktop.

jna coding

C

myc.c

#include <stdio.h>
int add(int x, int y)
{
  return x+y;
}

Java

JnaTest.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/3.0.9/jna-3.0.9.jar
javac -classpath $jna_jar JnaTest.java
java -classpath $jna_jar:. JnaTest
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment