mohamede1945
mohamede1945

Reputation: 7198

Android-NDK “java.lang.UnsatisfiedLinkError”

I am new to NDK.

I have a cpp file which has the following function

/* 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!");
}

The Java class that calls it

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

The make file

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

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

include $(BUILD_SHARED_LIBRARY)

The problem is that when I call the native function I got the

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

Upvotes: 2

Views: 3244

Answers (3)

Nidhin
Nidhin

Reputation: 1838

To use c calling conventions in cpp you can surround methods with

extern "C" { /*methods*/ };

Eg:

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

Upvotes: 0

mohamede1945
mohamede1945

Reputation: 7198

Actually I figured out that I need to add

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

Upvotes: 6

InflexCZE
InflexCZE

Reputation: 732

There is error in native code in method paremers

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

replace

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

Upvotes: 0

Related Questions