How The JNI Works
In the JNI framework, native functions are implemented in separate .c or .cpp files. (C++ provides a slightly simpler interface with JNI.) When the JVM invokes the function, it passes a JNIEnv
pointer, a jobject
pointer, and any Java arguments declared by the Java method. A JNI function may look like this:
The env
pointer is a structure that contains the interface to the JVM. It includes all of the functions necessary to interact with the JVM and to work with Java objects. Example JNI functions are converting native arrays to/from Java arrays, converting native strings to/from Java strings, instantiating objects, throwing exceptions, etc. Basically, anything that Java code can do can be done using JNIEnv
, albeit with considerably less ease.
For example, the following converts a Java string to a native string:
//C++ code extern "C" JNIEXPORT void JNICALL Java_ClassName_MethodName (JNIEnv *env, jobject obj, jstring javaString) { //Get the native string from javaString const char *nativeString = env->GetStringUTFChars(javaString, 0); //Do something with the nativeString //DON'T FORGET THIS LINE!!! env->ReleaseStringUTFChars(javaString, nativeString); } /*C code*/ JNIEXPORT void JNICALL Java_ClassName_MethodName (JNIEnv *env, jobject obj, jstring javaString) { /*Get the native string from javaString*/ const char *nativeString = (*env)->GetStringUTFChars(env, javaString, 0); /*Do something with the nativeString*/ /*DON'T FORGET THIS LINE!!!*/ (*env)->ReleaseStringUTFChars(env, javaString, nativeString); } /*Objective-C code*/ JNIEXPORT void JNICALL Java_ClassName_MethodName(JNIEnv *env, jobject obj, jstring javaString) { /*DON'T FORGET THIS LINE!!!*/ JNF_COCOA_ENTER(env); /*Get the native string from javaString*/ NSString* nativeString = JNFJavaToNSString(env, javaString); /*Do something with the nativeString*/ /*DON'T FORGET THIS LINE!!!*/ JNF_COCOA_EXIT(env); }Native data types can be mapped to/from Java data types. For compound types such as objects, arrays and strings the native code must explicitly convert the data by calling methods in the JNIEnv
.
Read more about this topic: Java Native Interface
Famous quotes containing the word works:
“... no one who has not been an integral part of a slaveholding community, can have any idea of its abominations.... even were slavery no curse to its victims, the exercise of arbitrary power works such fearful ruin upon the hearts of slaveholders, that I should feel impelled to labor and pray for its overthrow with my last energies and latest breath.”
—Angelina Grimké (18051879)