Android-eclipse-ndk&jni

Source: Internet
Author: User

Android-eclipse-ndk&jni

1. Introduction to NDK (★)background of 1.1 NDK generation

The Android platform has supported C and C + + development since its inception. As we all know, the Android SDK is based on Java implementations, which means that third-party apps that are developed based on the Android SDK must use the Java language. But this is not the same as "third-party apps can only use Java." When the Android SDK was first released, Google announced that its virtual machine Dalvik supported JNI programming, which means that third-party applications could call their own C dynamic library through JNI, i.e., on Android, the "java+c" programming is always possible.

However, Google also said that the use of Native SDK programming compared to the Dalvik virtual machine has some disadvantages, the Android SDK documentation, no JNI help found. Even if third-party application developers use JNI to complete their own C dynamic-link library (SO) development, how so is packaged with the app as an APK and released? There are also technical barriers in this. For example, the program is more complex, compatibility is difficult to protect, unable to access the framework api,debug more difficult and so on. Developers need to use them at their own discretion.

So the NDK was born. The NDK full name is native development Kit.

The release of the NDK enabled the development of "Java+c" to become officially supported by the official development approach. The NDK will be the beginning of the Android platform to support c development.

1.2 Why use the NDK

1. Protection of the code. Because the Java layer Code of the APK is very easy to decompile, and the C + + library is difficult to decompile.

2. The existing open Source library is easy to use. Most of the existing open source libraries are written in C + + code.

3. Improve the efficiency of the execution of procedures. Use c development for application logic that requires high performance to improve application execution efficiency.

4. Easy to transplant. The library can be used in other embedded platforms easily.

1.3 NDK Introduction

1.NDK is a collection of a range of tools

The NDK provides a range of tools to help developers quickly develop C (or C + +) dynamic libraries and automatically package so and Java applications together as APK. The NDK integrates the cross compiler and provides the corresponding MK file isolation CPU, platform, ABI and other differences, developers simply need to modify the Mk file (stating "which files need to compile", "compilation characteristics Requirements", etc.), you can create a so.

2.NDK provides a stable, feature-limited API header file declaration

Google expressly declares that the API is stable and supports the currently published API in all subsequent releases. As seen from this version of the NDK, these APIs support a very limited number of features, including: C standard library (LIBC), Standard math Library (LIBM), compression library (LIBZ), log Library (Liblog).

installation of the 1.4 NDK

Download for 1.NDK

The official http://developer.android.com/tools/sdk/ndk/index.html of the NDK, because the official website in foreign countries, domestic access can not, must be FQ. So I offered to download a good NDK tool on the Baidu Network for everyone to download. Http://pan.baidu.com/s/1jGpCDKi

2. Unzip the NDK into a directory that does not contain spaces and Chinese

I unzipped the NDK in the D:\software\ndkr9\android-ndk-r9b.

1.5 NDK directory structure Description

Build: This directory holds a MK script using the NDK, the Mk script specifies the compilation parameters

Docs: This directory holds the NDK's use Help documentation

Platforms: This is a platform (x86,arm,mips)-related C language Library and header file related to each Android version

Prebuilt: Precompiled working Directory

Samples: The demo program is stored

Sources: stored in the NDK toolchain C-language source code

Tests: test-related files

Toolchains: Tool chain, storage of three kinds of structure of the static library and other files

The Ndk-build.cmd:window platform uses the NDK commands

The Ndk-build:linux platform uses the NDK commands

2. Introduction to JNI (★ ¡ï)

Here's a simple JNI case to demonstrate how to use JNI programming.

Create a new Android project, "Getting Started with JNI," as shown in the project's final directory structure.

Define a native method in the Mainactivity.java class

Create a folder in the project and directory JNI, the directory name is a convention (the contract is better than the configuration) good, can not be another name.

Create the hello.c source file under the JNI directory, and the file name can be created according to the rules that are known as the name. The HELLO.C code listing is as follows.

: The above code is simple, but the jni.h header file and method name must be described separately.

1) The jni.h header file is located in the NDK installation directory/platforms/android-*/(a platform)/usr/include directory, as

The above platform refers to the CPU three architectures such as. We choose any one of the architecture, but for the mobile phone CPU with the most ARM architecture, x86 second, the least MIPS architecture.

2) naming rules for C source file method names in Jni

The naming convention here refers to the C language method that corresponds to the native method in the Java file, while the other methods in the C language are named as long as they conform to the C language rules. Jstring java_com_itheima_jnihello_mainactivity_helloc(jnienv* env, Jobject obj), Jstring is the method return value type, We can think of jstring as a type of intermediate conversion between string and C in Java, and Java is different from the C language data type, and they have to be implemented through a mediation to invoke each other, which is defined in the jni.h header file. For more conversion types, the 2nd chapter of this document will be described in more detail.

The first letter of the method name must be Java, capitalize the first word, and then underline _, and then connect the package, class, and method that the method is in with "_". For example, the Helloc method in the Com.itheima.jnihello.MainActivity class is transformed into a method named Java_com_itheima_jnihello_mainactivity_helloc in the C language. .

Two of the formal parameters of a method are required, that is, regardless of whether the method in Java is a physical parameter, but the corresponding method in C must have jnienv* env, and Jobject obj, if the Java method also uses other formal parameters, then in C language strictly in order in the Jobject Can be followed by the obj parameter.

The above env represents a pointer to the JVM, and obj is the Java object that invokes the method.

Compiling hello.c into a hello.so file using the NDK tool

To facilitate the use of the NDK tool's Ndk-build.cmd command directly in the console, we first set the directory where the Ndk-build.cmd resides as a system environment variable. After the environment variable is configured, entering ndk-build.cmd on the command line will prompt you as follows:

Switch the current directory to the project directory where hello.c is located

If you enter Ndk-build.cmd directly then the following exception will appear:

When this error occurs, we do not tell the NDK that we want to compile the C-language source code into a target file. To tell the NDK to compile the C source file into a target file, we need to add the Android.mk configuration file to the JNI directory in the project.

Add the ANDROID.MK configuration file under the JNI directory of the current project, which can be copied from the instance code of the NDK installation directory and then modified.

ANDROID.MK file list below, we only need to modify the Local_module and local_src_files two parameters. The Local_module parameter is the name of the specified compiled target file, in fact the compiled target file named Libhello.so,local_src_files specifies the source file to compile.

In cmd, the current directory is switched to the directory where the hello.c is located, and then the Ndk-build.cmd command is re-executed, and the cmd display appears as shown in this successful compilation.

View the project directory structure and discover that there are two more folders Armeabi and x86 in the Libs directory, each containing a libhello.so dynamic link library. This also represents a dynamic library in the current project that supports both the ARM architecture and the CPU of the x86 architecture.

: Maybe you didn't generate these two files at the same time because I introduced the application.mk file in my project, so you need to introduce the file.

APPLICATION.MK file list:

The list actually has only one line of content, and the first line is a comment. The App_abi parameter specifies which platforms are supported for the target file to be generated, and the default is Armeabi if you want to support more than one platform and then write out other platform names.

Calling the C language in Mainactivity.java

Running the above works, the effect is as follows:

: If we compile the so file on the arm platform, but deploy it to the emulator on the x86 platform, we will not find the libhello.so exception when running.

3. JNI Specification (★)3.1 JNI data types and structure

1) Basic Data type

The corresponding table for the JNI base type and the local equivalent type is as follows:

Java type

Local C type

actual representation of C type

( Win32 )

Description

Boolean

Jboolean

unsigned char

Unsigned, 8-bit

Byte

Jbyte

Signed Char

Signed, 8-bit

Char

Jchar

unsigned short

Unsigned, 16-bit

Short

Jshort

Short

Signed, 16-bit

Int

Jint

Long

Signed, 32-bit

Long

Jlong

__int64

Signed, 64-bit

Float

Jfloat

Float

32 Guests

Double

Jdouble

Double

64 guests

void

void

N/A

N/A

2) reference type, JNI also contains a reference type that corresponds to a different Java object, and the organization hierarchy of the JNI reference type is as follows:

3.2 Jni Interface function naming method

1) Type signature

The type signature of the Java Virtual machine is as follows:

Type signature

Java type

Z

Boolean

B

Byte

C

Char

S

Short

I

Int

J

Long

F

Float

D

Double

Lfully-qulitied-class;

Fully qualified class

[Type

type[] Array

(argtypes) RetType

Method type

For example, the type signature of the Java method int feet (int n, String s,int [] arr) is as follows:

(iljava/lang/string; [i) I

Inside the parentheses is the parameter, I represents the first argument int, ljava/lang/string; indicates that the second parameter is the fully qualified Java.lang.String type, [I represents the third argument is an array of type int, the parentheses are followed by the return value type, I means the return value is of type int.

2) How to name the Jni interface function of general function

The general JNI interface functions are named as follows:

Java_ Package Name _ Class Name _ Method name.

For example, the C language implementation function of the Mainactivity class int Getintfromc () method under the Com/itheima package under a project is named as follows:

Jint JAVA_COM_ITHEIMA_MAINACTIVITY_GETINTFROMC (jnienv* env,jobject obj)

Where the package name contains a "/" should all be underlined instead, its locally implemented parameters and return values should also be converted to the JNI type.

3) How to name the JNI interface function of overloaded functions

In addition to the JNI implementation of the overloaded function, the type signature should be added as the difference between the function with the same name, and its interface function is named as follows: Java_ Package Name _ Class Name _ Method name _ parameter signature.

For example, the C language implementation function of the Mainactivity class under the Com/itheima package under a project is named as follows: GETINTFROMC (int n, String s,int [] arr) method.

Jint java_com_itheima_mainactivity_getintfromc_iljava_lang_string_2_3i

(jnienv* env, Jobject obj, Jint N, jstring S, Jintarray arr).

JNI uses a name-scrambling scheme when naming a function to ensure that all Unicode characters can

Convert to a valid C function name, all "/", whether in the package name or the fully qualified class name, use "_" instead, with _0, ", _9 to replace the escape character, as follows:

Escape character sequence

Said

_0xxxx

Unicode character XXXX

_1

character "_"

_2

characters in a signature " ; "

_3

characters in a signature "["

3.3 Jni functions and APIs

The main concern in this document is the conversion process between the C + + data type and the JNI local type, a process in which some data transformations need to be done using a series of methods of the JNIEnv object.

1) jstring converted to C-style string

char* test = (char*) (*env)->getstringutfchars (env,jstring,null);

When you are finished, you should call:

(*env)->releasestringutfchars (env, jstring, test);

Frees resources.

2) C-style string converted to Jstring

Char charstr[50];

Jstring Jstr;

JSTR = env-Newstringutf (CHARSTR);

3) A section of the char* buffer obtained in C is passed to Java

In Jni, new a byte array, and then use the

(*env)->setbytearrayregion (env, ByteArray, 0, Len, Buffer) operation copies the buffer into the array.

This approach is mainly for the presence of "" "in buffer, if read in the form of a C-style string, you will lose the character after" \ ".

4) Array manipulation

JNI function

Function

Getarraylength

Returns the number of elements in an array

Newobjectarray

Creates an array of raw data types of a specified length

Getobjectarrayelement

return Object elements of an array

Setobjectarrayelement

Set Object elements of an array

Getobjectarrayregion

Copies the contents of the original data type array into a pre-allocated memory cache

Setobjectarrayregion

Set the value of an array in the cache

Releaseobjectarrayregion

Release getobjectarrayregion Allocated Memory

: For array operations of basic data types such as Int,char, replace the related object name with the corresponding base data type name as the correlation function.

The method selection for array manipulation is based on the needs of the consumer, and if the user needs to copy and manipulate the array in memory then generally use the getobjectarrayregion and setobjectarrayregion functions. Otherwise, the setobjectarrayelement and getobjectarrayelement functions are generally used.

4. Case-Bank Login System (★)

Requirement: Suppose the bank's login module is written in C, but our Android application wants to log into the banking system, then it needs to be implemented by JNI.

Create a new Android project "CCB Client", the project directory structure such as.

Create the Jni folder in the project, and then copy the jni.h, Android.mk, and application.mk from the JNI Primer project.

Create the Login.c file in the JNI directory to implement the logon business logic in the file. The code listing is as follows.

is to use the NDK tool to compile the login.c into a dynamic library file. Local_src_files to modify the Android.mk file before compiling: = Login.c

Written in the Mainactivity.java class

The layout file is relatively simple and is not given here.

Run the above code and run the result as follows:

5. Installation of the CDT plugin (★)5.1 CDT Introduction

The CDT project is dedicated to providing a fully functional, C + + integrated development environment (Integrated development environment,ide) for the Eclipse platform. The CDT is an open source project implemented entirely in Java (licensed under Common public License) as a set of plugins for the Eclipse SDK platform. These plug-ins add a/C + + perspective to the Eclipse Workbench (Workbench), which is now supported by a number of views and wizards, as well as advanced editing and debugging support.

download of the 5.2 CDT

The CDT plugin can be installed online through eclipse, but is limited to cross-country network access and is generally not very useful. So here I'm mostly talking about how to install offline.

Download the CDT offline installation package. The CDT installation package for different versions of Eclipse is as follows, and you can download it directly from my Baidu Web disk. Considering the most recent ADT we use, it is recommended to choose the 8.5.0 version of CDT.

Cdt-8.5.0-for-eclipse-luna http://pan.baidu.com/s/1c0m1k0w

Cdt-8.3.0-for-eclipse-kepler http://pan.baidu.com/s/1kT21QOf

Cdt-8.1.2-for-eclipse-juno Http://pan.baidu.com/s/1qWAzjBI

Select Eclipse's Help->install New software ..., which pops up the following dialog box

Click the Add button and enter name in the dialog box that pops up. In the location bar if you enter an HTTP address to have Eclipse automatically download the installation from the network, here we click the Archive button to find our pre-downloaded offline installation package. then click OK.

Tick all of the CDT plug-ins, and remove the check-out from the bottom of the Internet inspection Update, then click Next until finish.

After installation, there will be a C + + option in File->new->other, such as.

In open perspective, there are also multiple options for the C + + view, such as.

Once installed, we will be able to develop our C + + project in Eclipse. But there are not many opportunities for our Android developers to use. Even if you are developing C + + projects, most programmers will not choose to develop on the Eclipse platform. Eclipse is more focused on the development of Java language projects, such as Java EE, Android.

Android-eclipse-ndk&jni

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.