Use of JNI and Android ndk

Source: Internet
Author: User

In fact, the difference between JNI and ndk can be understood as follows: JNI is a set of Sun APIs, while ndk is more like a tool, which is provided by Google itself and compiled by C/C ++.

I. About JNI:

JNI is Java Native intereface, which provides interfaces for Java applications to call local methods. The primary goal of JNI is to call local methods in the form of library files, and is DLL in windows, so in UNIX.

Defect: the Java program runs on the JVM to ensure platform independence. However, if the Java program calls the native code (C/C ++) through JNI, the platform independence is lost.

Advantages: Reuse C/C ++ code and call local libraries.

Note: JNI is not available on the j2_based platform. External DLL calls cannot be performed as in JNI. If you need to use a DLL, you can only add the static link when "Designing" The j2-vm, on the premise that you can get the source code of the Symbian Java Vm and then add the DLL to the VM, and can replace the original Symbian Java virtual machine .. (From a csdn user)

Ii. Use of JNI

The general steps for JNI program development are as follows:

1. Compile the call class in Java: design idea:Place local methods in a single class to minimize future porting.

2: Use javah to generate the header file of the C/C ++ native function. javah does not use the default internal command and must specify the path.

3: Call other required functions in C/C ++ to implement native functions

4: add all native libraries and resources dependent on the project to Java. Library. Path of the Java project.

5: Release Java and dynamic libraries (DLL/so are placed in the same level directory of the jar package)

 

Iii. Notes

1: When a. h file is generated using javah: unsatisfiedlinkerror + method name Error

2: Do not use JNI in an applet. This is because a security exception may occur in the applet.

3: encapsulate all local methods in a single class, which calls a single DLL. For each target operating system, you can replace this DLL with a version specific to the appropriate platform. In this way, you can minimize the impact of local code and include the porting problems that will be needed in the future.

4: The local method should be simple. Minimize the dependency of the generated DLL on any third-party runtime DLL. Make local methods as independent as possible to minimize the overhead required to load DLL and applications. If you must run the DLL, it should be provided along with the application.

5: when the local code is running, it does not effectively prevent array out-of-bounds errors or indirect errors caused by incorrect pointer references. Therefore, you must ensure the stability of the local code, because any errors may cause the Java virtual machine to crash.

Iv. JNI data type ing

 

Jniexport void jnicall java_helloworld_print (jnienv * ENV, jobject OBJ ){}

Jniexport and jnicall are macro definitions in JNI. h. Make sure that this function is visible outside the local database, and the C compiler performs correct call conversion. C/C ++ function name: Java + package name + class name + function name. It corresponds to the Function Name Of The. h file generated by the javah command. If the function name is incorrect, unsatisfiedlinkerror will occur.


 

JNI transmits the objects in Java as a C pointer to the local method. This Pointer Points to the internal data structure in the JVM, and the internal data structure is invisible in the memory. The local code must select an appropriate JNI function in jnienv to operate on objects in the JVM.

The jnienv interface pointer of the first parameter points to a function table, and each entry in the function table points to a JNI function. Local methods often use these functions to access the data structure in JVM.

The second parameter varies depending on whether the local method is a static method or an instance method. When the local method is a static method, the second parameter represents the class (jclass) of the local method; when the local method is an instance method, the second parameter represents the object (jobject) of the local method ).

Corresponding basic data type:

JNI processes the basic and reference types differently. The ing of basic types is one-to-one. For example, the int type in Java directly corresponds to the jint type in C/C ++.

For reference types:

JNI transmits the objects in Java as a C pointer to the local method. This Pointer Points to the internal data structure in the JVM, and the internal data structure is invisible in the memory. The local code must select an appropriate JNI function in jnienv to operate on objects in the JVM. For example, if the string corresponds to jstring, the local code can only be accessed through JNI functions such as getstringutfchars.

 

Java type

Local type

Description

Boolean

Jboolean

C/C ++ 8-bit integer

Byte

Jbyte

C/C ++ signed 8-digit integer

Char

Jchar

C/C ++ unsigned 16-bit integer

Short

Jshort

C/C ++ signed 16-bit integer

Int

Jint

C/C ++ signed 32-bit integer

Long

Jlong

C/C ++ signed 64-bit integer e

Float

Jfloat

C/C ++ 32-bit floating point

Double

Jdouble

C/C ++ 64-bit floating point

Object

Jobject

Any Java object, or no corresponding Java type object

Class

Jclass

Class Object

String

Jstring

String object

Object []

Jobjectarray

Array of any object

Boolean []

Jbooleanarray

Boolean Array

Byte []

Jbytearray

Bit Array

Char []

Jchararray

Struct Array

Short []

Jshortarray

Short integer Array

Int []

Jintarray

Integer Array

Long []

Jlongarray

Long Integer Array

Float []

Jfloatarray

Floating Point Array

Double []

Jdoublearray

Double Floating Point Array

 

Function

Java array type

Local type

Getbooleanarrayelements

Jbooleanarray

Jboolean

Getbytearrayelements

Jbytearray

Jbyte

Getchararrayelements

Jchararray

Jchar

Getshortarrayelements

Jshortarray

Jshort

Getintarrayelements

Jintarray

Jint

Getlongarrayelements

Jlongarray

Jlong

Getfloatarrayelements

Jfloatarray

Jfloat

Getdoublearrayelements

Jdoublearray

Jdouble

 

 

 

Function

Description

Getfieldid

Obtains the ID of an instance's domain.

Getstaticfieldid

Obtain the ID of a static domain.

Getmethodid

Obtain the ID of an instance method.

Getstaticmethodid

Obtain the ID of a static method.

 

 

Java type

Symbol

Boolean

Z

Byte

B

Char

C

Short

S

Int

I

Long

L

Float

F

Double

D

Void

V

Objects object

Lfully-qualified-class-name; L Class Name

Arrays Array

[Array-type [array type

Methods Method

(Argument-types) Return-type (parameter type) return type

 

You cannot directly access the local type in JNI. You need to access it through the corresponding function.

JNI supports String Conversion between Unicode and UTF-8. Supports C/C ++ APIs

// C format
(* Env)-> <JNI function> (ENV, <parameters>)
// C ++ format
Env-> <JNI function> (<parameters>)

 

To avoid ugly function names, jni api provides methods to register a function ing table with the Java Virtual Machine. In this way, when Java calls the native interface, the Java Virtual Machine does not need to decide which function to call based on the function name. You can directly query the table to find the function to be called.

 

Call the Java method from the local code. That is, Callbacks (callback) in the local method ).

Comparison of native/Java and Java/native and Java/Java efficiency: Native/Java <Java/native <Java/Java

 

V. References in JNI

JNI supports three types of references: local reference, global reference, and weak global reference.

Local references and global references have different lifecycles. When the local method returns, the local reference is automatically released. The global reference and weak reference must be released manually.

Local references or global references prevent GC from reclaiming the objects they reference, but weak references do not.

Not all references can be used in all cases. For example, it is illegal to access a local reference after a local method creates a local reference and returns it.

 

1: local reference:

A local reference is only valid before the local method to be created returns. After the local method is returned, the local reference is automatically released. (The same is true for static local objects)

In fact, the local reference in JNI is different from the local variable in C language. Its validity period is the context in which the current native function is called. The call context I understand is the calling process of the Java Virtual Machine. Native functions are called by Java virtual machines. After native functions are executed, the control process is returned to the Java Virtual Machine. In native functions, local variables are created by calling the JNI interface of Java Virtual Machine by native code. After the native function is executed, if the local reference is not displayed and deleted by the native code, the local reference is still valid in the Java Virtual Machine. The Java Virtual Machine determines when to delete this object. This is different from the local variable concept in C language. This can also explain why the natvie function can return a local reference.

 

Local references are very important to show release in native code.

(If the native function you implement is a tool function, it will be called frequently. If you do not delete a local reference in the native function, a new local reference will be created each time you call this function on the Java Virtual Machine, resulting in too many local references. In particular, this function is frequently called in native code, and the control of the Code is not handed back to the Java Virtual Machine. Therefore, the Java Virtual Machine has no chance to release these local variables .)

Jniapi has three functions to process local references: ensurelocalcapacity, pushlocalframe, and poplocalframe.

You can use the stack to understand local variables.

 

 

2: global reference:

Global reference can be used across methods and threads until it is manually released. Like local references, global references also prevent the objects referenced by them from being recycled by GC. Newglobalref and deleteglobalref.

3: weak references

Weak references are created using newglobalweakref and released using deleteglobalweakref. Similar to global references, weak references can be used across methods and threads. Unlike global references, weak references do not prevent GC from reclaiming the objects inside the VM to which it points. Newweakglobalref and deleteweakglobalref. Check its validity when using it.

 

When a JNI reference is created, in addition to the objects in the JVM to which it points, the reference itself consumes a certain amount of memory. As a JNI programmer, you should be very careful about the number of references used by the program in a given period of time. Creating a large number of references that are not immediately recycled in a short period of time will cause memory overflow.

 

6. dll related to so

 

Ndk:

I. About ndk

Native Development Kit. Ndk provides a series of tools to help developers quickly develop C (or C ++) dynamic libraries, and can automatically package so and Java applications into APK together. The APIS supported by Google's ndk are very limited, including: C standard library (libc), standard library (libm), compressed Library (libz), and log Library (liblog)

 

Ii. cygwin

 

Download and install cygwin. cygwin is a UNIX simulation environment running on Windows.

 

For more information, see Baidu Library.

3. Android. mk file and makefile

Translation documents can be found on EOE.

Local_path: = $ (call my-DIR)

Include $ (clear_vars)

Local_module
: = Helloworld

Local_src_files: = helloworld. c

 

Include $ (build_shared_library)

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.