Differences between C and C ++ for Android NDK Jni Development
Because Android official NDK examples are mostly written in C language, various errors may occur when we want to use C ++ for development. The following are some differences: the differences are marked in red in the Code: 1. First, let's use an example written in C: (1) hello. c file. There is no reference in C, and the passed env is a two-level pointer. Use (* env)-> to call the method and the method must be passed in env. 1 # include <jni. h> 2 3 jstring Java_com_example_Hello_hello (JNIEnv * env, jobject thiz) {4 return (* env)-> NewStringUTF (env, "Hello Jni ----> C! "); 5} (2) Android. mk file. Change the suffix. c copy code 1 LOCAL_PATH :=$ (call my-dir) 2 3 include $ (CLEAR_VARS) 4 5 LOCAL_MODULE: = hello6 LOCAL_SRC_FILES: = hello. c7 8 include $ (BUILD_SHARED_LIBRARY) Copy Code 2. another example written in C ++: (1) hello. cpp file. In C ++, env is a level-1 pointer. env-> is used to call the method. env is not required. during compilation, C ++ solves the function polymorphism problem, the function name and parameter are combined to generate an intermediate function name, but the C language does not. Therefore, the corresponding function cannot be found during the link, in this case, the C function needs to use extern "C" to specify the link. This tells the compiler that keep my name and do not generate an intermediate function name for the link; exter "C" {jni code }. Copy code copy code 1 # include <jni. h> 2 3 # ifdef _ cplusplus 4 extern "C" {5 # endif 6 jstring Java_com_example_Hello_hello (JNIEnv * env, jobject thiz) {7 return env-> NewStringUTF ("Hello Jni ----> C ++! "); 8} 9 # ifdef _ cplusplus10} 11 # endif copy code (2) Android. mk file. Change the suffix. cpp copy code 1 LOCAL_PATH :=$ (call my-dir) 2 3 include $ (CLEAR_VARS) 4 5 LOCAL_MODULE: = hello6 LOCAL_SRC_FILES: = hello. cpp7 8 include $ (BUILD_SHARED_LIBRARY)