Differences between C and C ++ for Android NDK Jni Development

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.