我正在使用JNA在NetBeans中开发
Java项目.根据
JNA documentation,我可以通过将它放在jar中来使我的DLL可用于Java:
Make your native library available on your classpath, under the path {OS}-{ARCH}/{LIBRARY}, where {OS}-{ARCH} is JNA’s canonical prefix for native libraries (e.g. win32-x86, linux-amd64, or darwin). If the resource is within a jar file it will be automatically extracted when loaded.
这就是我想要做的,所以我在src / win32-x86-64下的项目中包含了DLL:s.如果我用netbeans构建一个jar文件,然后在另一个项目中包含jar文件,一切正常,JNA找到我的库没有问题.这是我在jna.debug_load上得到的:
Looking in classpath from sun.misc.Launcher$AppClassLoader@15db9742 for /com/sun/jna/win32-x86-64/jnidispatch.dll
Found library resource at jar:file:/C:/MyNetBeansProject/dist/lib/jna-4.2.2.jar!/com/sun/jna/win32-x86-64/jnidispatch.dll
Looking for library 'MyLibrary'
Adding paths from jna.library.path: null
Trying MyLibrary.dll
Adding system paths: []
Trying MyLibrary.dll
Looking for lib- prefix
Trying libMyLibrary.dll
Looking in classpath from sun.misc.Launcher$AppClassLoader@15db9742 for MyLibrary
Found library resource at file:/C:/MyNetBeansProject/build/classes/win32-x86-64/MyLibrary.dll
Looking in C:/MyNetBeansProject/build\classes\win32-x86-64\MyLibrary.dll
Found library 'MyLibrary' at C:/MyNetBeansProject/build\classes\win32-x86-64\MyLibrary.dll
显然,不使用jar中的DLL.而是使用构建文件夹中的DLL.
现在,如果我将jar文件移动到另一个文件夹并将其包含在我的项目中,我会得到一个UnsatisfiedLinkError. JNA提供以下输出:
Looking in classpath from sun.misc.Launcher$AppClassLoader@70dea4e for /com/sun/jna/win32-x86-64/jnidispatch.dll
Found library resource at jar:file:/C:/SomeFolder/lib/jna-4.2.2.jar!/com/sun/jna/win32-x86-64/jnidispatch.dll
Looking for library 'MyLibrary'
Adding paths from jna.library.path: null
Trying MyLibrary.dll
Adding system paths: []
Trying MyLibrary.dll
Looking for lib- prefix
Trying libMyLibrary.dll
Looking in classpath from sun.misc.Launcher$AppClassLoader@70dea4e for MyLibrary
Found library resource at jar:file:/C:/SomeFolder/MyNetBeansProject.jar!/win32-x86-64/MyLibrary.dll
它看起来像JNA在jar中找到DLL,但它不会尝试提取它.我在我的临时文件夹中找不到它(JNA提取它自己的内部DLL).
这里有什么问题?为什么JNA不提取文件?我怎样才能解决这个问题?
(我不知道这是否相关,但我应该提到我的DLL依赖于jar中同一个文件夹中的多个其他DLL文件.不确定JNA是否会自动为它提取它们,但到目前为止似乎JNA甚至没有提取我实际使用的DLL.)
编辑:找到jnidispatch.dll似乎没有问题.根据jna.debug_load.jna设置为true时的输出,该文件在JAR中找到并解压缩到临时文件夹.
最佳答案 无法加载DLL时JNA显示错误“UnsatisfiedLinkError”.如果您的DLL需要系统路径中不存在的另一个自定义DLL,它将失败,因为JNA不会自动提取此dll.
JNA作为Java库不知道系统库的依赖性,因此无法从jar中提取.解决方案是指定JNA Java接口中的所有依赖项.
操作系统的幕后发生了什么
最后,操作系统根据主可执行文件的请求加载库.在这种情况下,主要可执行文件是java.exe或(jvm.dll).如果系统无法在路径中找到库,则会失败并且java会生成异常.