Java LoadLibrary 未解决的依赖关系,但依赖的 dll 在同一目录中

2022-01-25 00:00:00 dll java java-native-interface

I'm having problems with Java loading a native dll, as it happens 64-bit Windows 7. FWIW the package is ZeroMQ but what matters is that the jar requires a native dll to load, called jzmq.dll. This in turn depends on libzmq.dll (and some standard libraries). I've copied both dlls into target/lib and set java.language.path to target/lib.

If I write:

System.loadLibrary("jzmq");

I get an UnsatisfiedLinkError of Can't find dependent libraries. However if instead I say

System.loadLibrary("libzmq");
System.loadLibrary("jzmq");

Then there is no problem and jzmq.dll loads successfully.

Inside the accompanying jar it just has System.loadLibrary("jzmq") and I'd prefer not to have to fiddle with the dependency in my code. It's not clear to me why the dependency doesn't load automatically or what I'd need to do to get it to work properly.

Thanks in advance for any help!

解决方案

Dependencies of libraries are resolved by the operating system not by the Java runtime. When you set java.library.path to your directory the Java runtime knows where to look for libraries but the operating system will still not find the dependencies. For Windows to find your library you have to set your directory in the PATH environment variable.

PS: The reason it works when you load the dependent library first is, that it will be in the process' address space afterward and Windows will find it there and won't need to find it in the file system

PPS: articles saying that dependent libraries will automatically be found on Windows if you put them in the same directory are only telling half of the truth. The reason this works is that a) they're talking about dependencies of excutables not other libraries and b) when you start an executable without an explicit working directory, the working directory will be the directory that has the executable in it and Windows automatically adds the working directory to the search path (therefore libraries that are in the same directory will be found).

相关文章