c++ - Jni 不工作

标签 c++ string java-native-interface unsatisfiedlinkerror java.library.path

这是我的 Java 代码。

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);
    }
}

我正在使用 jdk1.7.0_17 。 这是我的 C++ 代码

#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());
    }
}

我使用下面的注释运行这个程序。

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

现在我收到以下错误。我不知道如何解决它。

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)

最佳答案

尝试像这样启动您的应用程序:

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

并且在此之前,将您的库从 NativePrompt.so 重命名为 libNativePrompt.so

希望这对你有帮助。

关于c++ - Jni 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15540559/

相关文章:

java - JNI/JNA 与 Runtime.getRuntime().exec(String)?

java - 使用 JNI : are we releasing objects property? 内存泄漏

c++ - 错误 LNK2019 : unresolved external symbol (libJPEG compiling and linking)

c++ - 与 MinGW (v.4.3.0) 和 libhid 的链接问题

Java 格式化输出问题

javascript - 保留 int.toString() 中的前导零

c++ - 在 C++ 中从键盘完成 cin

c++ - 在 Windows 7 上使用 Windows Media Foundation 将原始音频文件转换为 AAC

javascript - 如何在 JavaScript 中将原始字符串(字符串文字)设为 "instanceof"

安卓 NDK/JNI : "No rule to make target" error when compiling my hybrid iOS/Android project