Search code examples
javacjava-native-interfacejna

Loading a custom library with JNA on Windows


I have a .c file in which are defined methods with JNIEXPORT and i don't know how use these methods in a Java class importing them with JNA

I try to read this guide but I don't understand if it's possible to link a specific .c file.

Can someone help me?


Solution

  • Yes, it's possible, build and compile a shared library as you usually do and load it with Native.loadLibrary.

    C:

    #include <stdio.h>
    
    void exampleMethod(const char* value)
    {
        printf("%s\n", value);
    }
    

    Compile it in the usual way (showing gcc on linux here):

    gcc -c -Wall -Werror -fPIC test.c
    gcc -shared -o libtest.so test.o
    

    Java:

    import com.sun.jna.Library;
    import com.sun.jna.Native;
    
    public class TestJNA{
      public interface CLibrary extends Library {
        public void exampleMethod(String val);
      }
    
      public static void main(String[] args) {
        CLibrary mylib = (CLibrary)Native.loadLibrary("test", CLibrary.class);
        mylib.exampleMethod("ImAString");
      }
    
    }
    

    Since you are having issues finding the library, this is usually fixed configuring the java.library.path adding a new location where .so/.dll will be searched:

    java -Djava.library.path=c:\dlllocation TestJNA
    

    Alternatively you can set it directly from your code before loading the library (works with JNI, should work with JNA too, but i didn't try it):

    String libspath = System.getProperty("java.library.path");
    libspath = libspath + ";c:/dlllocation";
    System.setProperty("java.library.path",libspath);
    
    //Load your library here