Java and native code communication involves native method declarations and definitions, data types, reference data type operations, NIO operations, access domains, exception handling, native threads
1. Declaration and definition of native methods
The Declaration and definition of the native method has been said a little bit in the previous article, this time detailed analysis. Based on the Javah auto-generated header file, you can see the declaration and definition of the native method, for example:
- Jniexport jstring jnicall java_com_shamoo_helljni_hellojni_stringfromjni (jnienv *, jobject);
Although the native method on Java does not have any parameters, it is the native method of the Jni interface with two parameters. JNIENV * is an interface pointer to the JNI function table, and Jobject is the Java object reference that invokes the method. As can be seen from the above method, the method in Java code in the Com.shamoo.helljni package, class is Hellojni.
JNIENV * Pointers: Native methods use the functions of the virtual machine through the various functions provided by the JNIENV * pointer.
Native methods are called in different ways in C and C + +, for example:
- /* C */
- Return (*ENV)->newstringutf (env, "Hello World");
- /* C + + *
- Return Env->newstringutf ("Hello World");
In the C language, JNIEnv is a pointer to the JNINATIVEINTERFACE structure that must be dereferenced. And the first parameter is env, learned C and C + + language know, C language is a process-oriented language, NEWSTRINGUTF is just a function pointer, call the method is not clear the caller, so to pass env, and C + + is not used, because C + + is Object-oriented language, this does not explain
2. Example method and static method
The instance method and static method definition of the native method are also different, the above stringfromjni is the way of the instance method definition, the second parameter binds to the Java object reference. The second parameter of a static method is Jclass, which is bound to a class and belongs to a class method. For example:
- Jniexport jstring jnicall java_com_shamoo_helljni_hellojni_stringfromjni (jnienv *, jclass);
Android NDK Development article: Java and Native code communication (native method declaration and definition and data type)