JNI changes C to C ++

I have a simple piece of code that I want to use in a 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 * .c file - everything is fine, but I want this C ++ code, I will rename this file to * .cpp (and change Android.mk). Everything compiled, but when I try to use this function the way I used it in C, I have an error.

* I also modify the body of func:

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

Try using this:

 public native String stringFromJNI(); static { System.loadLibrary("hello-jni"); } 

And I got this 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 cannot understand why the same code runs in C and crashes (runtime) in C ++.

+4
source share
2 answers

To allow function overloading, C ++ uses something called mangling. This means that the function names do not match in C ++, as in regular C.

To suppress this name, you need to declare the functions as extern "C" :

 extern "C" jstring Java_com_example_ndk_MainActivity_stringFromJNI( JNIEnv* env, jobject thiz) { return (*env)->NewStringUTF(env, "Hello from JNI !"); } 
+18
source

To use C calling conventions in C ++ code , combine your functions with

 extern "C" { /* your C API */ } 
+2
source

Source: https://habr.com/ru/post/1433374/


All Articles