Analysis of JNI function registration process, analysis of jni Function
When we call Native code in java, it is generally implemented through JNI. We only need to load local data in the java class. the so library file, declare the native method, and then call the method where it needs to be called. The specific implementation of the native method in java is handed over to the Native layer. What are the prerequisites for correctly calling the corresponding functions in local code in java? The answer is to establish a one-to-one correspondence between native methods in java and functions in local code through a certain mechanism. What is this mechanism? Is the JNI function registration mechanism.
JNI functions can be registered in two ways: static registration and dynamic registration. The following describes the two implementation methods respectively.
1. Static registration.
1. Implementation principle: Establish a one-to-one correspondence between java methods and JNI functions based on the function name.
2. Implementation Process:
① Write java code;
② Compile the java code to generate the. class file;
③ Use the javah command to generate a JNI. h file using the generated. class file;
④ The generated JNI header file contains the declaration of Java functions at the JNI layer;
3. Disadvantages:
① Writing is inconvenient, because the name of the JNI-layer function must follow a specific format and the name is particularly long;
② It will lead to a huge workload for programmers, because JNI header files must be written for all java classes declared with native functions;
③ The program running efficiency is low, because when calling the native function for the first time, you need to search for the corresponding local function in the JNI Layer Based on the function name and then establish the corresponding relationship. This process is time-consuming.
2. Dynamic Registration.
1. Implementation principle: directly tell the native function its pointer to the function in JNI;
2. Implementation Process:
① Use the JNINativeMethod struct to save the correspondence between Java Native functions and JNI functions;
② Store the correspondence between all native functions and JNI functions in a JNINativeMethod array;
③ After loading the JNI dynamic library through System. loadLibrary in Java, call the JNI_OnLoad function to start dynamic registration;
④ The AndroidRuntime: registerNativeMethods function will be called in JNI_OnLoad for function registration;
⑤ AndroidRuntime: registerNativeMethods finally calls jniRegisterNativeMethods to complete registration.
3. Advantage: the disadvantage of static registration is overcome.