Detailed introduction to the registration process of JAVA JNI function
When we call Native code in java, it is generally implemented through JNI. We only need to load the local .so library file in the java class, declare the native method, and then call it where it needs to be called. As for the specific implementation of the native method in java, it is all handed over to the Native layer. What is the prerequisite for us to correctly call 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 certain mechanisms. So what is this mechanism? It is the registration mechanism of JNI functions.
There are two ways to register JNI functions, one is the static registration method, and the other is the dynamic registration method. Let’s introduce these two implementation methods below.
1. Static registration.
1. Implementation principle: Establish a one-to-one correspondence between a java method and a JNI function based on the function name.
2. Implementation process:
①Writing Java code;
② Compile java code and generate .class files;
③ Use the javah directive to generate JNI .h file using the generated .class file;
④ The generated JNI header file contains the declaration of Java functions in the JNI layer;
3. Disadvantages:
①Writing is very inconvenient because the names of JNI layer functions must follow a specific format and the names are particularly long;
② It will cause a lot of work for programmers, because JNI header files must be written for all java classes that declare native functions;
③The program is running inefficient, because when calling a native function for the first time, you need to search for the corresponding local function in the JNI layer according to the function name, and then establish a corresponding relationship. This process is time-consuming.
2. Dynamic registration.
1. Implementation principle: directly tell the native function its pointer to the corresponding function in JNI;
2. Implementation process:
① Use the structure JNINativeMethod to save the correspondence between Java Native functions and JNI functions;
② Save 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 and start dynamic registration;
④The AndroidRuntime::registerNativeMethods function will be called in JNI_OnLoad for function registration;
⑤The final call to jniRegisterNativeMethods in AndroidRuntime::registerNativeMethods complete registration.
3. Advantages: Overcoming the disadvantages of static registration.
Thank you for reading, I hope it can help you. Thank you for your support for this site!