Search code examples
javacmacosjava-native-interface

Unsatisfied Link Error When Loading JNI Library


I am writing a simple Hello World Java program to call code from a native library. However, when I run the program, I receive the following error:

 Exception in thread "main" java.lang.UnsatisfiedLinkError: no TestJNI in java.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1764)
    at java.lang.Runtime.loadLibrary0(Runtime.java:823)
    at java.lang.System.loadLibrary(System.java:1044)
    at TestJNI.<clinit>(TestJNI.java:4)

Below is the code:
Java:

//filename: TestJNI.java

public class TestJNI{

    static{
        System.loadLibrary("TestJNI");
    }   

    private native void helloWorld();

    public static void main(String[] args){
        new TestJNI().helloWorld();
   }
}

C:

//filname:TestJNI.c

#include <jni.h>
#include <stdio.h>
#include "TestJNI.h"

JNIEXPORT void JNICALL Java_TestJNI_helloWorld(JNIEnv *env, jobject thisObj){
    printf("Hello World!\n");
    return;
}

The C file is compiled with the following compiler, flags and arguments:
clang -o TestJNI.jnilib -I/System/Library/Frameworks/JavaVM.framework/Headers -lc -shared TestJNI.c
Then the Java application is run as below:
java -Djava.library.path=. TestJNI

I am compiling and running the files on Mac OS X Yosemite. Does anyone have any idea what I am doing wrong?


Solution

  • Verify that java.library.path variable points to the directory which contains the TestJNI library. You can try

    System.setProperty("java.library.path", "...directory path...");

    Alternatively, use System.load("...full path to TestJNI..."); which takes the full path to the library (including the file extension). (System.loadLibrary infers the file extension I believe)