4

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?

1 Answers1

4

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.

Samuel Audet
  • 4,964
  • 1
  • 26
  • 33
  • Is very stressfull for hard drive but is the only way to keep the .so file in the jar I think! – Davide TheSgrash Nov 08 '14 at 15:08
  • @DavideTheSgrash Well, that's an OS issue really: They need an actual library file. Most support mounting the temporary directory in RAM though. – Samuel Audet Nov 08 '14 at 22:53
  • We have the same requirement and this method is not working for us. Linux OS and Java8. Are we missing anything here? – Milli Aug 31 '15 at 16:52
  • No. No. In our case we already have the .so file packaged in the jar. We were trying to write/add a class in the jar itself to load the so file during runtime. We used the above code do so. The result is, the lib is extracted to temp directory and the `System.load()` is also executed, but when tried to access the lib it fails. Are we missing something ? – Milli Sep 02 '15 at 14:13
  • Thanks, Very useful I am working on this issue from the last 2 days and finally got the solution. – Swapnil1156035 Feb 27 '20 at 11:58