Android-NDK“java.lang.UnsatisfiedLinkError”

时间:2012-07-28 21:49:50

标签: android android-ndk

我是NDK的新手。

我有一个cpp文件,它具有以下功能

/* This is a trivial JNI example where we use a native method
 * to return a new VM String. See the corresponding Java source
 * file located at:
 *
 *   apps/samples/hello-jni/project/src/com/example/hellojni/HelloJni.java
 */
JNIEXPORT jstring JNICALL
Java_com_some_player_MainActivity_stringFromJNI( JNIEnv* env,
                                                  jobject thiz )
{
    return env->NewStringUTF("Hello from JNI!");
}

调用它的Java类

package com.some.player;
public class MainActivity extends Activity {
    public native String stringFromJNI();
    static {
        System.loadLibrary("hello-jni");
    }

     @Override
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);

       TextView tv = (TextView) findViewById(R.id.textView);
       tv.setText(stringFromJNI());
    }
}

制作文件

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := hello-jni
LOCAL_SRC_FILES := hello-jni.cpp

include $(BUILD_SHARED_LIBRARY)

问题是,当我调用本机函数时,我得到了

07-28 23:42:34.256: E/AndroidRuntime(32398): java.lang.UnsatisfiedLinkError: stringFromJNI

3 个答案:

答案 0 :(得分:6)

实际上我发现我需要添加

extern "C" {
    JNIEXPORT jstring JNICALL Java_com_some_player_MainActivity_stringFromJNI( JNIEnv* env, jobject thiz )
};

答案 1 :(得分:0)

方法专家中的本机代码存在错误

return env->NewStringUTF("Hello from JNI!");

替换

return (*env)->NewStringUTF(env, "Hello from JNI !");

答案 2 :(得分:0)

在cpp中使用c调用约定 你可以用

包围方法
extern "C" { /*methods*/ };

例如:

#include <jni.h>
#include <string>
extern "C" {
JNIEXPORT jstring JNICALL
Java_com_test_ndk_ndktest_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}
JNIEXPORT jint JNICALL
Java_com_test_ndk_ndktest_MainActivity_add(JNIEnv *env, jobject instance, jint a, jint b) {
    return (a + b);
}
};