I have a simple piece of code that i want to use in my java (android) application:
#include <string.h>
#include <jni.h>
jstring
Java_com_example_ndk_MainActivity_stringFromJNI( JNIEnv* env,
jobject thiz)
{
return (*env)->NewStringUTF(env, "Hello from JNI !");
}
If i use C and call this file *.c - everything is ok, but i want this code on C++, i rename this file to *.cpp (and change Android.mk). Everything is compiled but when i try to use this function in the way i've used it in C, i have a error.
*Also i modify body of the func:
return env->NewStringUTF("Hello from JNI !");
Try to use this:
public native String stringFromJNI();
static {
System.loadLibrary("hello-jni");
}
And got such an error:
09-10 17:55:46.410: W/dalvikvm(6339): No implementation found for native Lcom/example/ndk/MainActivity;.stringFromJNI ()Ljava/lang/String;
09-10 17:55:46.410: E/AndroidRuntime(6339): java.lang.UnsatisfiedLinkError: stringFromJNI
09-10 17:55:46.410: E/AndroidRuntime(6339): at com.example.ndk.MainActivity.stringFromJNI(Native Method)
09-10 17:55:46.410: E/AndroidRuntime(6339): at com.example.ndk.MainActivity.onCreate(MainActivity.java:22)
I can't understand why the same code run in C and fail (runtime) in C++.
To allow for overloading of functions, C++ uses something called name mangling. This means that function names are not the same in C++ as in plain C.
To inhibit this name mangling, you have to declare functions as extern "C"
:
extern "C" jstring
Java_com_example_ndk_MainActivity_stringFromJNI( JNIEnv* env,
jobject thiz)
{
return (*env)->NewStringUTF(env, "Hello from JNI !");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With