Search code examples
c++stringjava-native-interfaceunsatisfiedlinkerrorjava.library.path

Jni not working


This is my Java code.

class NativePrompt {
    private native String getInput(String prompt);  //native method
    static   //static initializer code
    {
        System.loadLibrary("NativePrompt");
    } 

    public static void main(String[] args)
    {
        NativePrompt NP = new NativePrompt();
        String sName = NP.getInput("Enter your name: ");
        System.out.println("Hello " + sName);
    }
}

I'm using jdk1.7.0_17 . This is my c++ code

#include "NativePrompt.h" 
#include "jni.h"
#include "string"
#include "iostream"
#include "vector"

using namespace std;
/*
 * Class:     NativePrompt
 * Method:    getInput
 * Signature: (Ljava/lang/String;)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_NativePrompt_getInput
    (JNIEnv *env, jobject obj, jstring prompt){

    string sEntry;
    const char *str;
    str = env->GetStringUTFChars(prompt, NULL);
    if (str == NULL) {
        return env->NewStringUTF("");
    }
    else{
    cout << str;
        //Frees native string resources
        env->ReleaseStringUTFChars(prompt, str);

        //reads n-consecutive words from the 
        //keyboard and store them in string
        getline(cin, sEntry);

        return env->NewStringUTF(sEntry.c_str());
    }
}

I run this program using the below comments.

javac NativePrompt.java

javah NativePrompt

g++ -o NativePrompt.so -shared -I /usr/lib/jvm/jdk1.7.0_17/include -I /usr/lib/jvm/jdk1.7.0_17/include/linux NativePrompt.cpp

export LD_LIBRARY_PATH='/home/user/jniwork/'

java NativePrompt

Now I'm getting the below error. I don't know how to resolve it .

Exception in thread "main" java.lang.UnsatisfiedLinkError: no NativePrompt in java.library.path at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1860) at java.lang.Runtime.loadLibrary0(Runtime.java:845) at java.lang.System.loadLibrary(System.java:1084) at NativePrompt.(NativePrompt.java:5)


Solution

  • try launching your application like this:

    java -Djava.library.path=/home/user/jniwork/ NativePrompt
    

    and also before, rename your library from NativePrompt.so to libNativePrompt.so

    Hope this helps you out.