在 Windows 上使用 JNA 加载自定义库

Loading a custom library with JNA on Windows

我有一个 .c 文件,其中用 JNIEXPORT 定义了方法,我不知道如何在 Java class 中使用这些方法,用 [=12 导入它们=]

我尝试阅读 this guide 但我不明白是否可以 link 特定的 .c 文件。

有人可以帮助我吗?

是的,可以像往常一样构建和编译共享库并使用 Native.loadLibrary 加载它。

C:

#include <stdio.h>

void exampleMethod(const char* value)
{
    printf("%s\n", value);
}

以通常的方式编译它(在 linux 此处显示 gcc):

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");
  }

}

由于您在查找库时遇到问题,这通常是通过配置 java.library.path 添加一个新位置来搜索 .so/.dll 来解决的:

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

或者,您可以在加载库之前直接从您的代码中设置它(适用于 JNI,应该也适用于 JNA,但我没有尝试):

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

//Load your library here

根据 "uraimo" 对 jna 的回答,它应该使用 jna.library.path 而不是 java.library.path,这应该可以解决位置问题。