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 told a bit in the previous article, this time specific analysis. According to Javah's own initiative generated header files. can see the Declaration and definition of the native method, such as:
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. From the above method can be seen. The Com.shamoo.helljni package for the method in Java code. 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 + +. Like what:
/* 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, which must be dereferenced. And the first parameter is env, learned C and C + + languages are known. C is a process-oriented language, and Newstringutf is just a function pointer. Calling this method is not clear to the caller, so it is necessary to pass ENV, while C + + does not. Because C + + is an object-oriented language. That's not an explanation .
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 the instance method is defined. The second parameter is bound to the Java object reference. The second parameter of a static method is Jclass, which is bound to a class. belongs to a class method. Like what:
Jniexport jstring jnicall java_com_shamoo_helljni_hellojni_stringfromjni (jnienv *, jclass);
3. Data type
Java's basic data types are directly preceded by a J in Jni, such as the Java int corresponding to the jint ...
The reference type of Java is different from the base data type, and the corresponding relationship is as follows:
Java.lang.Class-Jclass
Java.lang.Throwable-Jthrowable
Java.lang.String-Jstring
Java.lang.Object-Jobject
The array is directly appended to it, such as byte[], Jbytearray, object[] and Jobjectarray ...
Android NDK Development Chapter (IV): Java and Native code communication (native method declaration and definition and data type)