JNA 在 Eclipse 中找到库 运行,但在构建 JAR 文件时找不到

JNA finds library running in Eclipse but not when a built JAR file

我正在编写一个需要使用.dll 文件的程序。当我的程序启动时,执行以下代码:

public static void main(String[] args)
{
    String dLLURL = "C:/Program Files (x86)/Location of DLL";
    System.setProperty("jna.library.path", dLLURL);
    System.setProperty("jna.debug_load", "true");
    System.setProperty("jna.debug_load.jna", "true");
    Application.launch(args);
}

然后我执行 DllInterface dllinterface = (DllInterface) Native.loadLibrary( "dllName.dll", DllInterface.class);

...加载正确的 dll 并允许我使用它。 JNA 输出以下 (这次使用 DLL 的实际 name/path)

Trying (via loadLibrary) jnidispatch
Looking in classpath from sun.misc.Launcher$AppClassLoader@e2f2a for /com/sun/jna/win32-x86/jnidispatch.dll
Found library resource at jar:file:/C:/Users/bengs_000/Downloads/jna.jar!/com/sun/jna/win32-x86/jnidispatch.dll
Trying C:\Users\BENGS_~1\AppData\Local\Temp\jna-792348840\jna2314341730536889248.dll
Found jnidispatch at C:\Users\BENGS_~1\AppData\Local\Temp\jna-792348840\jna2314341730536889248.dll
Looking for library 'RailDriver.dll'
Adding paths from jna.library.path: C:\Program Files (x86)\Steam\SteamApps\common\RailWorks\plugins
Trying C:\Program Files (x86)\Steam\SteamApps\common\RailWorks\plugins\RailDriver.dll
Found library 'RailDriver.dll' at C:\Program Files (x86)\Steam\SteamApps\common\RailWorks\plugins\RailDriver.dll

这是我在 Eclipse IDE 中 运行 程序时发生的情况。效果很好!

但是,当我 build/run 程序作为 .jar 时,应用程序说找不到 DLL(尽管在正确的位置查找)和 returns 以下消息:

Trying (via loadLibrary) jnidispatch
Looking in classpath from java.net.URLClassLoader@677327b6 for /com/sun/jna/win32-x86-64/jnidispatch.dll
Found library resource at jar:rsrc:jna.jar!/com/sun/jna/win32-x86-64/jnidispatch.dll
Trying C:\Users\BENGS_~1\AppData\Local\Temp\jna-792348840\jna8530559464473818762.dll
Found jnidispatch at C:\Users\BENGS_~1\AppData\Local\Temp\jna-792348840\jna8530559464473818762.dll
Looking for library 'RailDriver.dll'
Adding paths from jna.library.path: C:\Program Files (x86)\Steam\SteamApps\common\RailWorks\plugins
Trying C:\Program Files (x86)\Steam\SteamApps\common\RailWorks\plugins\RailDriver.dll
Adding system paths: []
Trying C:\Program Files (x86)\Steam\SteamApps\common\RailWorks\plugins\RailDriver.dll
Looking for lib- prefix
Trying libRailDriver.dll
Looking in classpath from java.net.URLClassLoader@677327b6 for RailDriver.dll
There was an error finding your raildriver.dll file

如您所见,找到 .dll 文件的路径完全相同,但它在 Eclipse 中工作,而不是编译后的 .jar 文件!

你能帮我找出问题所在吗?需要注意的一件事是.dll 文件存储在 Program Files 的 32 位部分中,而我的计算机是 64 位的。我正在使用 Java 32 位编译和 运行 Eclipse 中的程序。当然它应该用 Java 32 位构建 .jar 对吧?

我找到了解决办法!

背景

我知道这个问题与我想使用的 .dll 是 32 位的,而我的计算机是 64 位的有关。在 Eclipse IDE 中,我是 运行 使用 Java 32 位的应用程序(我知道我应该这样做以确保兼容性)。

当运行.jar文件时,Java默认为64位版本;与我在 Eclipse 中测试它的方式不同。

解决方案

要强制用户使用Java 32 位,您需要将.jar 打包成一个.exe 文件。我使用 Launch4J 来做到这一点。 Launch4j 中有一个参数允许您指定要使用 Java 的哪个系统。它位于 "Search Options" 部分的 JRE 选项卡下。通过将其更改为“仅 32 位”,.jar 文件将在 Java 32 位下启动,从而缓解问题!

希望这对某些人有所帮助!