JNI learning---register native function

There are two ways to register native functions: static registration and dynamic registration.

static registration method

Find the corresponding JNI function according to the function name. When the Java layer calls the function, it will search for the function from the corresponding JNI. If there is no function, an error will be reported. If it exists, an association will be established, and this function will be used directly when calling in the future. This part of the operation is done by the virtual machine.

The static method is to traverse the relationship between java and jni functions according to the function name, and requires the name of the jni layer function to follow a specific format. The disadvantages are:

  • The jni layer function generated by javah is very long;
  • When the native function is called for the first time, it is necessary to search the corresponding jni layer function according to the name to establish an association, which affects efficiency.

Dynamic Registration Method

JNI allows you to provide a function mapping table and register it with the Java virtual machine, so that Jvm can use the function mapping table to call the corresponding function, and you don't need to use the function name to find the function that needs to be called.

JNI_OnLoad() function

The JNI_OnLoad() function is called when the VM executes the System.loadLibrary(xxx) function. It has two important functions:

  • Specify the JNI version: Tell the VM which JNI version the component uses (if the JNI_OnLoad() function is not provided, the VM will default to using the oldest JNI version 1.1), if you want to use a new version of JNI, such as JNI 1.4, you must The JNI_OnLoad() function returns the constant JNI_VERSION_1_4 (the constant is defined in jni.h) to inform the VM.
  • Initialization setting: When the VM executes the System.loadLibrary() function, it will immediately call the JNI_OnLoad() method, so it is most appropriate to initialize various resources in this method.

RegisterNatives

RegisterNatives is defined in AndroidRunTime:

jint RegisterNatives(jclass clazz, const JNINativeMethod* methods,jint nMethods)

clazz: Java class object
Methods: Native methods in the class
nMethods: Number of local methods in the class

Summarize

Compared with function name mapping, the advantage of native method registration is that it does not need to use javah to generate a C++ header file, nor does it need to use the long C++ function names automatically generated by javah. Often, when there are many native functions, the extension is more flexible. At the same time, the Java virtual machine does not need to perform mapping processing, which greatly improves the running speed and efficiency.

Guess you like

Origin blog.csdn.net/johnWcheung/article/details/129441596