Java Reference
In-Depth Information
native
code gains access to these JNI library functions via the JNIEnv pointer, which
is a pointer into a C/C
These C and C
++
functions appear in the JNI library. C and C
++
function table. You can, however, think of the JNIEnv
variable as a pointer into the Java “environment.” It is automatically provided
to your C/C
++
++
code by the JNI system when the JVM routes a method call
from Java to your native code. It is always the first of the two “extra” function
arguments that appear in the native function signature.
As an example, let's see howaCimplementation calls the GetMethodID()
function. If we added a call to GetMethodID() to our nativeHelloWorld imple-
mentation, this JNI function would be accessed as follows:
JNIEXPORT void JNICALL
Java - javatech - jni22 - JNIHelloWorld - nativeHelloWorld
(JNIEnv *jenv, jobject jo) {
jmethodID mid =
(*jenv)->GetMethodID (jenv, <actual arguments>);
...
}
Here the Java interface pointer is named jenv in the function signature. This
jenv pointer is used to call the GetMethodID() function as shown. Note
the double dereferencing (i.e. the use of the construct (*jenv)- > ) and note
that jenv is also passed as the first argument to the function. (We discuss the
< actual arguments > later when we describe GetMethodID() in more
detail.) This code is, admittedly, a little ugly, but it demonstrates how the Java
interface pointer is used to call JNI functions from the C language. Any call to
any JNI function in C looks similar.
The C
syntax is somewhat cleaner. The extra level of indirection is
unneeded and the interface pointer is not passed as the first argument in the
function call:
++
jmethodID mid = jenv->GetMethodID (<actual arguments>);
This cleaner way of calling JNI functions is possible because of some magic
worked by the jni.h header file when using C
++
.Weuse C
++
in the rest of
the examples in this topic for convenience.
The interface pointer received in a native call is valid only for the current Java
thread. The JVM always passes a valid interface pointer when it makes a native
method call, and if there are multiple calls to a native method, the JVM always
passes the same interface pointer as long as all those calls are from the same
Java thread. However, if a native method is called from different Java threads,
the native implementation may receive different JNI interface pointers. A native
method implementation must not pass the interface pointer from one Java thread
to another. In general, one should just use the interface pointer received from the
Search WWH ::




Custom Search