简体   繁体   English

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

[英]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 我有一个.c文件,其中使用JNIEXPORT定义了方法,我不知道如何在Java类中使用这些方法通过JNA导入它们

I try to read this guide but I don't understand if it's possible to link a specific .c file. 我尝试阅读本指南,但我不知道是否可以链接特定的.c文件。

Can someone help me? 有人能帮我吗?

Yes, it's possible, build and compile a shared library as you usually do and load it with Native.loadLibrary . 是的,可以像通常那样构建和编译共享库,并使用Native.loadLibrary加载它。

C: C:

#include <stdio.h>

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

Compile it in the usual way (showing gcc on linux here): 以通常的方式进行编译(此处在Linux上显示gcc):

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

Java: 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.library.path来解决此问题,并添加新位置以搜索.so / .dll:

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): 或者,您可以在加载库之前直接从代码中进行设置(可与JNI一起使用,也应与JNA一起使用,但我没有尝试过):

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来解决位置问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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