System.loadLibrary failing on java 1.6 but working on java 1.5
I have ran into a peculiar problem on AIX 6.1 and SLES 11 . I am trying to load a so
file in Java using System.loadLibrary()
call. Below is sample program:
public class jniTest
{
public static void main(String[] args)
{
try
{
System.loadLibrary("libSample.so");
System.out.println("Loaded!!!");
}
catch(UnsatisfiedLinkError e)
{
System.out.println("unsati开发者_运维技巧sfiedlinkerror");
}
}
When I compile this piece of code with Java 1.5 it works properly. But when I compile it with Java 1.6 it says UnsatisfiedLinkError
. I don't understand how I could possibly be getting this error. The way I am running is:
javac jniTest.java
java -Djava.library.path=. jniTest
The so
file is place in the current directory from where I am running the code.
Before this, things I have tried:
giving the absolute path - didn't work
using
Runtime.getRuntime().loadLibrary()
- didn't work
Any idea what I am doing wrong?
I don't think you're supposed to have the ".so
" extension when using JNI. Try with just System.loadLibrary("libSample");
Just to expand on what Jim said: you don't need the .so extention or the 'lib' part of the file. This should work(at least, it works for me in 1.6):
try
{
System.loadLibrary("Sample");
System.out.println("Loaded!!!");
}
catch(UnsatisfiedLinkError e)
{
System.out.println("unsatisfiedlinkerror");
}
The first three things I think of:
- Make sure the library is on the java lib path (You've done this)
- Make sure you're using
System.loadLibrary()
correctly. If your library is called "libSample.so", the call should beSystem.loadLibrary("Sample")
. (This has been suggested in other answers) - Consider that there may be an issue with the library under OpenJDK, and that's the Java VM you're using. Run the command
java -version
and if part of the response is something likeOpenJDK Runtime Environment (build 1.6.0_0-b11)
, try installing the official Sun JDK and see if that works.
Another possibility is that your native functions in Java do not line up with the functions in the library. There is a very clearly defined naming convention for JNI functions. For example, if you have a function in java that's supposed to call a c/c++ library function:
package my.packagename;
public class Test {
static {
System.loadLibrary("Sample");
}
public native void testJNI(int arg1);
}
The corresponding function in c or c++ MUST be (Assuming your package name is "com.packagename"):
JNIEXPORT void JNICALL Java_my_packagename_Test_testJNI(JNIEnv* env, jobject obj, jint arg1) {
// ... code here
}
The reason I went through that is if the function names do not match, an UnsatisfiedLinkError is thrown.
精彩评论