简体   繁体   中英

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?

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

按照jna的“ uraimo”答案,应该使用jna.library.path而不是java.library.path来解决位置问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM