Calling C + + code on Android and iOS devices

Source: Internet
Author: User

Many Android and iOS projects, because of various reasons, have to call C + + code. This article focuses on using objective-c++, NDK technology, to invoke C + + code on iOS and Android devices.

Main working principle

The main working principle, as shown in. Google Android provides the NDK to support C + + code, while iOS can support the compile and run of C + + code through objective-c++ (*.MM). If a friend has delved into cocos2d-x, it should be very familiar with the above content. Well, don't say much nonsense, start offering dry goods.

C + + code that needs to be called

Let's write a simple C + + code so that it can be called on Android and iOS devices. For the sake of simplicity, and to be able to fully demonstrate the operation process, we designed the following C + + classes:

MyClz.hFile
#include <iostream>class MyClz {      public:       double getSum(const double num1, const double num2);};

In the MyClz.h header file above, we introduced and iostream declared a class MyClz that contains a public method getSum that is obvious: passing in a numeric value of two double, and then calculating and returning a number of two numbers.

MyCLz.cppFile
#include "MyClz.h"double MyClz::getSum(const double num1, const double num2){    return num1 + num2;}int main() {    return 0;}   

CPP file, we implement the content of the method declared in the header file MyClz.h getSum , calculate the number of two numbers, and feed it back to the caller.

Next, let's look at how to invoke the methods in the above class on Android and iOS devices MyClz getSum .

On Android device calls
  1. Download and configure Android Studio
    In this example, the latest version of Android Studio (v1.2.1.1) is used as the development environment. Download and install and download the appropriate Android SDK and configure the development environment to suit your needs.

    Please note: The following pages require "scientific Internet" for normal access
    Android studio:http://developer.android.com/sdk/index.html

  2. Download and configure the NDK
    The NDK is a set of tools that Google offers to call C + + code on Android devices. In some cases, there may be no way to use the Java language to accomplish tasks, only with the help of the underlying native code (native code) implementation. At this point, the NDK will come in handy. Download the NDK to the following address and unzip it to a path on your local disk.

    Please note: The following pages require "scientific Internet" for normal access
    Android ndk:http://developer.android.com/tools/sdk/ndk/index.html

  3. Create a new Android project
    Create a new Android project in Android Studio. If you get used to Eclipse+adt friends, you may feel an egg ache in Android Studio. However, based on my experience, Android Studio can completely replace Eclipse+adt as the mainstream Android IDE of the future. Moreover, since it is Google's main push products, it should be more and more attention, so get used to the good early.
    The general directory structure of the new good Android project is as follows:

    In the above directory structure, several files and folders that are critical to the developer are:
    {project_home}/appMain Directory of Android project
    {project_home}/app/build.gradleApp build configuration file
    {project_home}/app/srcProject Source Code
    {project_home}/local.propertiesSDK, ndk path configuration file

  4. Modify a {project_home}/local.properties file
    There is a default line for this file, which is the file path for the specified Android SDK, as we also need to use the NDK in our project. Modify the file, and then add the following to tell the IDE which NDK path to use:

    ndk.dir=/YourPathToAndroidNDK/Android-NDK-r10d
  5. Modify a {project_home}/app/build.gradle file
    In this file, add the NDK configuration at "appropriate location" as follows:

    android {      ....      defaultConfig {         ...         ndk {           moduleName "HelloJNI"           stl "stlport_static"         }      }    ...    }   

    When adding the above in a file, it is particularly important to note the moduleName value of the property setting, which I name HelloJNI , which can be written casually. This value will be required when you need to import lib in the Jni code (which will be mentioned later in the article).

  6. {project_home}/app/src/mainAdd a table of jni contents to a directory
    Add a new directory to the above directory and jni put the written MyClz.h and file in MyClz.cpp it.

  7. {project_home}/app/src/main/jniadd files to the directory MyClz-JNI.cpp
    Because a specification that was previously written MyClz.h and MyClz.cpp not compliant with JNI the file (a customer-supplied CPP file is rarely compliant with the JNI specification), we need to write a CPP file that is compliant with the JNI specification.
    In this step, the {project_home}/app/src/main/jni directory should contain MyClz.h , MyClz.cpp and MyClz-JNI.cpp three files.

  8. Writing MyClz-JNI.cpp the contents of a file

    #include <jni.h>#include <stdio.h>#include <string.h>#include "MyClz.h"extern "C" {    MyClz* clz;    JNIEXPORT jdouble JNICALL Java_com_baratsemet_android_wrapper_HelloWrapper_getSumFromJNI(JNIEnv* env,jdouble num1, jdouble num2) {       return clz->getSum(num1,num2);    }};

Please note:
The method name in the above class is the method name * * That conforms to the JNI specification. The method name must be Java_包名_类名_方法名(参数名) this way. If you do not understand the friend, you can consult the JNI documentation, here is not detailed.

    1. Writing a HelloWrapper.java file
      MyClz-JNI.cppas you can see from the method name in the above file: The package that we are going to write in HelloWrapper.java is: com.baratsemet.android.wrapper , so {project_home}/app/main/java create a new class file in the above package, and the contents of the file are HelloWrapper.java as follows:
    public class HelloWrapper {            static {               //注意这里导入的类库名称与「步骤5」中的moduleName匹配              System.loadLibrary("HelloJNI");            }            public native double getSumFromJNI(double num1,double num2);        }      
    1. In the menu bar, select BuildMake Project
      At this point, choose to Make Project see if there is an error. If there is an error, please check the log to exclude.

    2. Call the class where needed HelloWrapper

Questions:
When the above code is called on "simulator" and "Real machine", the result may be inconsistent, so let's think about it.

On an iOS device call

It's very, very easy to call the C + + code on an iOS device relative to Android. The approximate steps are as follows:

  1. Create a new iOS project in Xcode
    Create a new name HelloCPP for the iOS project, first. Choose the development language, you can choose Objective-c can also choose Swift, anyway can be called, anyway can be mixed use, feel free!

  2. MyClz.hdrag and MyClz.cpp drop files into the project
    because Xcode already has a main.m file as the entry for the project, please remove MyClz.cpp main函数 the file type .

  3. Create a new one Cocoa Class and name itMyClzWrapper
    Press the shortcut key command + N , and then select New "cocoa class" in the panel that pops up, and enter the name: Myclzwrapper.
    By default, the actions above generate one MyClzWrapper.h and a MyClzWrapper.m file, Modify the suffix of the myclzwrapper.m file to mm , so that the file can write C + + code, or you can write objective-c code ( Which is the legendary objective-c++ file)

    MyClzWrapper.hThe contents of the file:

    #import <Foundation/Foundation.h>  @interface MyClzWrapper : NSObject    +(double) getSumFromCPP:(double) number1 :(double) number2;@end    

    MyClzWrapper.mmThe contents of the file:

    #import "MyClzWrapper.h"  #import "MyClz.h"  @implementation MyClzWrapper      MyClz* clz = new MyClz();      +(double) getSumFromCPP:(double) number1 :(double) number2{          return clz->getSum(number1, number2);      }  @end      
  4. Call the file where needed MyClzWrapper.mm

Article source download

Please asynchronous Git@oschina Https://git.oschina.net/baratsemet/CPP_Andoird_iOS

Calling C + + code on Android and iOS devices

Related Article

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.