c12 c12 - 9 months ago 74
Java Question

Loading a Linux .so File at Java Runtime

I'm trying to load a linux .so file at runtime in Java, but I'm getting an UnsatisfiedLinkError. I'm passing in the -Djava.library.path=/Users/tom/codebase/jni/dist VM argument when running the below java main from my Test.class. The libSample.so file is in the /Users/tom/codebase/jni/dist directory. Any ideas? Thanks!

public class Test {

public static void main(String[] args) {
//prints /Users/tom/codebase/jni/dist


VM Argument:



Exception in thread "main" java.lang.UnsatisfiedLinkError: no Sample in java.library.path
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1758)
at java.lang.Runtime.loadLibrary0(Runtime.java:823)
at java.lang.System.loadLibrary(System.java:1045)
at Test.main(Test.java:9)

I also tried to use try the direct approach (using System.load) and got the below results if these help any Exception in thread "main" java.lang.UnsatisfiedLinkError: /Users/tom/codebase/jni/dist/libSample.so: no suitable image found. Did find: /Users/tom/codebase/jni/dist/libCiscoEnergyWiseJni.so: unknown file type, first eight bytes: 0x7F 0x45 0x4C 0x46 0x01 0x01 0x01 0x00

Answer Source

Libraries on Linux are often named in the pattern libXXX.so, and I believe Java follows that convention. So System.loadLibrary("Sample") may be looking for libSample.so. You can verify this by making a quick test program to call System.mapLibraryName and checking the output.

To resolve the issue, assuming this is in fact the problem you're having, you can either rename your library file or use System.load (not System.loadLibrary), which will load the library specified by the exact filename you pass it, without any transformations. The latter method is not portable across platforms, though.