Java: load shared libraries with dependencies

前端 未结 6 1833
别那么骄傲
别那么骄傲 2021-02-14 16:43

I am wrapping a shared library (written in C) with Java using JNA. The shared library is written internally, but that library uses functions from another external library, which

6条回答
  •  囚心锁ツ
    2021-02-14 17:29

    In order to fix your issue you can use this package: https://github.com/victor-paltz/global-load-library. It loads the libraries directly with the RTLD_GLOBAL flag.

    Here is an example:

    import com.globalload.LibraryLoaderJNI;
    
    public class HelloWorldJNI {
     
        static {
            // Loaded with RTLD_GLOBAL flag
            try {
                LibraryLoaderJNI.loadLibrary("/path/to/my_native_lib_A");
            } catch (UnsatisfiedLinkError e) {
                System.Println("Couldn't load my_native_lib_A");
                System.Println(e.getMessage());
                e.printStackTrace();
            }
    
            // Not loaded with RTLD_GLOBAL flag
            try {
                System.load("/path/to/my_native_lib_B");
            } catch (UnsatisfiedLinkError e) {
                System.Println("Couldn't load my_native_lib_B");
                System.Println(e.getMessage());
                e.printStackTrace();
            }
        }
        
        public static void main(String[] args) {
            new HelloWorldJNI().sayHello();
        }
     
        private native void sayHello();
    }
    

    It is using the same dlopen() trick as the previous answers, but it is packaged in a standalone code.

提交回复
热议问题