UnsatisfiedLinkError when using JNI?

2020-03-20 23:30发布

问题:

I want to call a C program from Java program using JNI in linux ubuntu.

I am new to this and I have tried the sample program given in http://www.ibm.com/developerworks/java/tutorials/j-jni/section2.html . I have already created the .java, .h , .c and .so files. But when i tried to run the program I am getting the following error.

Exception in thread "main" java.lang.UnsatisfiedLinkError: no Sample1 in java.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1738)
    at java.lang.Runtime.loadLibrary0(Runtime.java:823)
    at java.lang.System.loadLibrary(System.java:1028)
    at Sample1.main(Sample1.java:13)

回答1:

This exception is indicating that the .so is not available to the JVM.

Adding the directory where the .so exists to the LD_LIBRARY_PATH will resolve this. If the .so depends on other .so libraries the directories where these .so exist will also need added to LD_LIBRARY_PATH.



回答2:

I've just tried to get the same sample to work on my CentOS and got the same error as you. As already answered, JVM failed to find the so file needed. I succeeded to get it to work by following the steps below using gcc:

$ javac Sample1.java
$ javah Sample1
$ # Include paths must also be specified using -I option in the following gcc command line!
$ gcc -shared -I...snip... Sample1.c -o libSample1.so
$ # Library path for libSample1.so must also be specified!
$ java -Djava.library.path=...path/to/libSample1.so... Sample1

If you omit the "lib" prefix of the shared library, JVM fails to find it for some reason. I don't know why. I am not familiar with the naming convention of shared libraries in Linux.

I hope this post could help.