Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {
        System.out.println(System.getProperty("java.library.path")); 
                //prints /Users/tom/codebase/jni/dist
        System.loadLibrary("Sample");
    }

}

VM Argument:

-Djava.library.path=/Users/tom/codebase/jni/dist

Exception:

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

like image 247
c12 Avatar asked Nov 08 '11 22:11

c12


1 Answers

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.

like image 191
David Z Avatar answered Oct 10 '22 04:10

David Z