Search code examples
javac++dlljava-native-interfacedynamic-linking

How does a JNI DLL search for its dependent native DLL?


Say I have JNI.dll. It depends on native.dll. Now my Java application calls System.loadLibrary("JNI").

Will the following folder layout work?

MainFolder
    |--main.exe
    |--SubFolder
          |--JNI.dll
          |--native.dll

My guess is, there are 2 levels of dependency resolution.

[Level 1]:

System.loadLibrary("JNI") uses JVM property java.library.path to locate JNI.dll.

[Level 2]:

JNI.dll relies on Windows system mechanism to locate native.dll.

Is this correct?

If I set %_JAVA_OPTIONS% as -Djava.library.path=MainFolder\SubFolder, I think it can cover the search for JNI.dll. But will it cover the search for native.dll, too?

ADD 1

It seems my guess of 2 levels got confirmed from here: How to add native library to "java.library.path" with Eclipse launch (instead of overriding it)

See comment by kevin cline. But the mentioned solution with LD_LIBRARY_PATH environment variable only applies to Linux.

ADD 2

I think I didn't make my question clear. Let me put it this way.

My confusion is: the JNI.dll depends on native.dll. Both of them are not in the main.exe's current working directory. Actually they are in a sub folder of CWD.

If I run main.exe directly, I just need to set the java.library.path = <other path>\MainFolder\SubFolder. Both DLL are found correctly.

But if I run my project from Eclipse, besides setting the java.library.path, I have to put the "\MainFolder\SubFolder" in the %PATH% environment variable.

I just don't know why Eclipse is so different.


Solution

  • A similar link: Must I place all dependent DLLs into the JDK's bin folder?

    Inspired by this thread:System versus user PATH environmental variable...winmerge works only if I add the path to the user PATH

    I start to wonder maybe my User %Path% is too long. So I moved the folder path containing my dependent DLL from the end of User %PATH% to the beginning. It works now!

    At first, I conclude that one who implemented the Windows' DLL lookup algorithm has some truncation issue. And I almost consider it as another annoying Windows Bug.

    But I wrote another Windows application which has similar DLL dependencies to confirm my guess. That application works fine! So I have to review my conclusion.

    I checked my User %PATH% entry one by one, and place the folder to each possible location. And finally, I find the root cause.

    I have a C:\MinGW\bin entry in User %PATH%, which happens to contain a libstdc++-6.dll (977KB) but unfortunately, which isn't compatible with the one I need (825KB). It only works if I place my folder before MinGW.

    Now this issue seems resolved. But another one comes up, do I need to switch back and forth if I want to use both my DLL and the MinGW?