The registration process for the JAVA JNI function is described in detail

  • 2020-05-16 06:58:56
  • OfStack

The registration process for the JAVA JNI function is described in detail

When we call Native code in java, 1 is generally implemented by JNI, we only need to load the local.so library file in java class, declare native method, and then call it where we need to call it, as for the specific implementation of native method in java, it is all left to Native layer. What is the premise that we need to call the corresponding function in the local code correctly in java? The answer is to establish the 11 correspondence between the native method in java and the function in the local code through a 1-definite mechanism. What is this mechanism? That's the registration mechanism for the JNI function.

There are two ways to register the JNI function, one is static registration, the other is dynamic registration. Let's take a look at each of these implementations.

1. Static registration.

1. Implementation principle: according to the function name, the 11 corresponding relations between java method and JNI function are established.

2. Implementation process:

Writing java code;

(2) compile java code, generate.class file;

(3) having used the javah command, the generated.class file is used to generate JNI.h file;

(4) after the generation of JNI header file contains the Java function in the JNI layer declaration;

3. Disadvantages:

It is very inconvenient to write, because the name of JNI layer function must follow a specific format, and the name is very long;

This results in a lot of work for programmers, because they have to write JNI header files for all java classes that declare native functions;

(3) the program runs inefficiently, because when calling native function for the first time, it needs to search the corresponding local function in JNI layer according to the function name, and then establish the corresponding relationship, which is time-consuming.

2. Dynamic registration.

1. Implementation principle: directly tell native function the pointer of its corresponding function in JNI;

2. Implementation process:

Use structure JNINativeMethod to save the corresponding relationship between Java Native function and JNI function;

Save the corresponding relationship between all native functions and JNI functions in an JNINativeMethod array;

After loading the JNI dynamic library through System.loadLibrary in Java, the JNI_OnLoad function is called to start the dynamic registration;

JNI_OnLoad will call AndroidRuntime::registerNativeMethods function for function registration;

AndroidRuntime::registerNativeMethods finally calls jniRegisterNativeMethods to complete the registration.

3. Advantages: overcome the disadvantages of static registration.

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: