Load .so file from a jar

Davide TheSgrash picture Davide TheSgrash · Oct 30, 2014 · Viewed 7.5k times · Source

I made a library in C and I call it from Java with JNI so I have my package and a lib folder with the libMYLIB.so file. I recall it from Java writing:

static{
    System.loadLibrary("MYLIB");
}

If I execute it with the option -Djava.library.path=../lib it works well.

But I need to create a jar file with my package and lib folder; so I made it and import in a more complex project.

In the big project the classes of my package are seen and used but at run-time Java fails to load MYLIB.

Is it possible to tell Java to load it from jar file? How?

Answer

Samuel Audet picture Samuel Audet · Nov 7, 2014

First, we need to make sure the JAR file is in the class path. Then, here is a simple way of loading the library, assuming it is found under /com/example/libMYLIB.so in the JAR:

    InputStream is = ClassLoader.class.getResourceAsStream("/com/example/libMYLIB.so");
    File file = File.createTempFile("lib", ".so");
    OutputStream os = new FileOutputStream(file);
    byte[] buffer = new byte[1024];
    int length;
    while ((length = is.read(buffer)) != -1) {
        os.write(buffer, 0, length);
    }
    is.close();
    os.close();

    System.load(file.getAbsolutePath());
    file.deleteOnExit();

But this glosses over a lot of corner cases and portability issues that are covered by JavaCPP inside the Loader class.