Load multiple dependent libraries with JNA

后端 未结 2 2049
小蘑菇
小蘑菇 2021-01-07 10:52

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 workin

2条回答
  •  迷失自我
    2021-01-07 11:42

    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");
    }
    

提交回复
热议问题