Android JNI Learning Notes

Source: Internet
Author: User


JNI is the Java Native Interface (Java Local interface). JNI is not an Android-specific thing, he inherits from Java. But for Android, JNI is critical, and Android, as an embedded operating system, has a large number of drivers and hardware-related features that are implemented in C/s + +. It can be said that in Android, regardless of application level or system level development is inseparable from the JNI.


The implementation of the Java language cannot be separated from the JVM, so when it comes time to call the C + + layer in the Java layer, it is necessary to tell the JVM that the method represents the local function, where Iggy can find the function, and vice versa. However, calling C + + from the Java layer requires establishing an association between functions, and C + + to java. You must obtain a reference to the Java object before you can invoke the object's method (Java-only object-oriented).


It is important to note that both C + + and Java, and from Java to C + +, are run in one thread.


From Java to C + +

Loading JNI Dynamic Libraries

In order to be able to use JNI, it is necessary to load the dynamic library where C + + code resides into the memory space of the process before calling the local method. General use of the system's LoadLibrary () method between

Public  static void LoadLibrary (String libname);
It is worth mentioning that Libname is part of the name of the dynamic library we generate (note: Here is part), in Android, the name of the JNI dynamic library must start with "Lib", then generally our libname will remove the prefix "Lib" and the suffix ". So" or " . dll ". Join our local dynamic library file as "libjni.so", then our call is

System.loadlibrary ("JNI");

Note: The suffix of the dynamic library is ". So" in Linux, which is ". dll" in window.

Here we do not need to specify the specific road strength of our dynamic link library. The Android system will automatically look in the relevant system path.

In general , LoadLibrary () is executed in the static code block of the class (to ensure that the native method is loaded between calls, the static code block executes first);

public class sample{     static {          system.loadlibrary ("JNI");}     }

defining the native method

The Java layer declares that the native method is simple:

Private  static native  final void native_init ();

In the native method, you can use any type as a parameter, including basic object types, arrays, and complex objects. Calling the native method in Java is no different than a normal method.


JNI Dynamic Link Library

The difference between a JNI dynamic link library and a non-dynamic library is that the "jni_onloader" function is defined in the JNI dynamic library, which is system.loadlibrary () and is called by the system to complete the registration of the JNI function.

Jint Jni_onloader (javavm* vm, void* reserved)
InThe most important thing in "Jni_onloader" is to complete the registration of the JNI function through the Registernativemethods () function (complete the native method declared in the Java layer and the C-function association in C + +); Our JVM is able to find the corresponding C function when it runs the native method.

Jnitest.cpp

 #define LOG_TAG "Hello-jni" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include < assert.h> #include "jni.h" #include "JNIHelp.h" #include "android_runtime/androidruntime.h" Static Jint Com_jeason_ Jnitest_nadd (jnienv *env, Jobject obj, jint A, Jint b) {return (A * b);} Static Jninativemethod gmethods[] = {{"Nadd", "(II) I", (void *) Com_jeason_jnitest_nadd},};static int register_android_ Test_add (jnienv *env) {return android::androidruntime::registernativemethods (env, "com/jeason/jnitest/ Loadlibraryjavaclass ", Gmethods, Nelem (gmethods)); Jint jni_onload (JAVAVM *vm, void *reserved) {jnienv *env = null;if (vm->getenv (void * *) &env, jni_version_1_4)! = JN I_OK) {printf ("Error getenv\n"); return-1;} ASSERT (env! = NULL); if (Register_android_test_add (env) < 0) {printf ("Register_android_test_add error.\n"); return-1 ;} return jni_version_1_4;} 
prototype of the Registernativemethods () function:

int Registernativemethods (jnienv* env,const char* classname,const jninativemethos* gmethods,int numberMethods);

The second parameter, classname, refers to the full path of our Java class (called System.loadlibrary ()), but in the name '. ' You need to use the path character '/'.

The third parameter, Gmethods, is an array of jninativemethods types


typedef  struct {     const char* name;    Const char* Signature;    void*   fnptr;} Jninativemethods;

where name refers to the name of the native method declared in Java, signature refers to the native method parameter signature (explained later);

Fnptr refers to the native method corresponding to the local function pointer, generally void* (cannot be specified directly, generally only with the void*, when invoked in coercion type conversion)


Typically function prototypes are generally

Jniexport jint jnicall com_jeason_jnitest_jnitext_nadd (jnienv *env, Jobject obj, jint a,jint b);

Jniexport and Jnicall can be omitted


Loadlibraryjavaclass.java

public class Loadlibraryjavaclass {static {system.loadlibrary ("JNI"),} public native int nadd (int a, int b);}


Parameter signature


the parameter signatures in the native method use some abbreviation symbols to represent the parameter types, which are defined in the Java language. The signature consists of a parameter and a return value, and the argument must be enclosed in parentheses, and a pair of empty parentheses must be used when it is not. For example, "(I) V" means that the method has an integer parameter and no return value. "([IZ) I" means there are 2 parameters, the first is the shape array the second is a Boolean, the return value is shaping.

The specific correspondence is shown in the following two images:


The array starts with a "[" and is represented by two characters


The above is the basic data type, before we solve the JNI function registration problem, let's consider such a problem. The parameters passed by calling the native function in Java are Java data types, so what will these parameter types do to JNI? Here we have a new topic-data type conversion.


Data type conversions:

in the Java layer called the native function passed to the JNI layer parameters, the JNI layer will do some special processing, we know that the Java data types are divided into the basic data type and reference data type two, JNI layer is also differentiated treatment. Represents the conversion of the Java data type->native type.


Among the Java data types, in addition to the basic data types and Arrays in Java, class,string,throwable, the data types of all the remaining Java objects are represented in JNI with Jobject.

but is it all so simple?

{"MyWay", "(Ljava.lang.String; Ljava.lang.String; Landroid.bean.Bean;) V ", (void*) MyWay}

for the compilation of JNI:

Android.mk

Local_path: = $ (call My-dir) include $ (clear_vars) Local_src_files: =      jnitest.cpplocal_shared_libraries: = Libandroid_runtimelocal_module: = Libjniinclude $ (build_shared_library)



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android JNI Learning Notes

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.