Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JNI change C to C++

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++.

like image 250
dilix Avatar asked Nov 29 '22 14:11

dilix


1 Answers

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 !");
}
like image 84
Some programmer dude Avatar answered Dec 15 '22 06:12

Some programmer dude