Load multiple dependent libraries with JNA

2019-02-20 13:57发布

问题:

Is there a way in JNA to load multiple dependent libraries with Java?

I usually use Native.loadLibrary(...) to load one DLL. But I guess its not working this way because I assign this function call to the instance member.

回答1:

Let's say I have library foo and library bar. bar has a dependency on foo; it also has a dependency on baz, which we are not mapping with JNA:

public class Foo {
    public static final boolean LOADED;
    static {
        Native.register("foo");
        LOADED = true;
    }
    public static native void call_foo();
}

public class Bar {
    static {
        // Reference "Foo" so that it is loaded first
        if (Foo.LOADED) {
            System.loadLibrary("baz");
            // Or System.load("/path/to/libbaz.so")
            Native.register("bar");
        }
    }
    public static native void call_bar();
}

The call to System.load/loadLibrary will only be necessary if baz is neither on your library load path (PATH/LD_LIBRARY_PATH, for windows/linux respectively) nor in the same directory as bar (windows only).

EDIT

You can also do this via interface mapping:

public interface Foo extends Library {
    Foo INSTANCE = (Foo)Native.loadLibrary("foo");
}
public interface Bar extends Library {
    // Reference Foo prior to instantiating Bar, just be sure
    // to reference the Foo class prior to creating the Bar instance
    Foo FOO = Foo.INSTANCE;
    Bar INSTANCE = (Bar)Native.loadLibrary("bar");
}


标签: java dll jna