Java - Loading dlls by a relative path and hide them inside a jar

前端 未结 4 830
遇见更好的自我
遇见更好的自我 2020-11-28 11:05

PART 1

I am developing a Java application that should be release as a jar. This program depends on C++ external libraries called by JNI. To load them, I use the me

相关标签:
4条回答
  • 2020-11-28 11:37

    I don't believe you can load the DLL directly from the JAR. You have to take the intermediary step of copying the DLL out of the JAR. The following code should do it:

    public static void loadJarDll(String name) throws IOException {
        InputStream in = MyClass.class.getResourceAsStream(name);
        byte[] buffer = new byte[1024];
        int read = -1;
        File temp = File.createTempFile(name, "");
        FileOutputStream fos = new FileOutputStream(temp);
    
        while((read = in.read(buffer)) != -1) {
            fos.write(buffer, 0, read);
        }
        fos.close();
        in.close();
    
        System.load(temp.getAbsolutePath());
    }
    
    0 讨论(0)
  • 2020-11-28 11:41

    You need to prime the classloader with the location of the DLL -- but it can be loaded without extracting it from the jar. Something simple before the load call is executed is sufficient. In your main class add:

    static {
        System.loadLibrary("resource/path/to/foo"); // no .dll or .so extension!
    }
    

    Notably, I experienced basically the same issue with JNA and OSGi's handling of how the DLLs are loaded.

    0 讨论(0)
  • 2020-11-28 11:54

    This JarClassLoader aiming to solve the same problem:

    http://www.jdotsoft.com/JarClassLoader.php

    0 讨论(0)
  • 2020-11-28 11:55

    Basically this should work. As this is the way JNA does it, simply download it and study the code. YOu even have some hints to make this platform independent...

    EDIT

    JNA brings its native code along in the jar, unpacks the correct binary at runtime und loads it. This may be a good pattern to follow (if i got your question correct).

    0 讨论(0)
提交回复
热议问题