Java Reference
In-Depth Information
made no attempt to access fields or methods of Java objects. It did not do any
error checking and did not throw any exceptions. In this section, we go deeper
in the details of JNI and explain how to use JNI for more realistic examples. JNI
supports all the features just mentioned, and we need to know how to use them.
First, as we explain those features, one may think that JNI is unnecessarily
complicated. A somewhat complicated JNI function call is needed, for example,
to gain access to Java object fields. Why couldn't the Java designers simply permit
the native implementation to access the fields directly as, say, members of a C
data structure? In fact, an early (Java 1.0) native method interface did just that but
was abandoned in favor of the more general JNI as Java matured. The modern JNI
appears complicated because it is important to avoid exposing the JVM's internal
layout of Java objects to native code. Doing so would preclude ever changing the
internal implementation and also make efficient garbage collection difficult. (See
the JNI Specification [1] for more details about the design decisions.)
It is because of this generality that JNI appears complicated. Again, we claim
that JNI is not so much complex as it is verbose. Learning the concepts of JNI is
not difficult. Applying them requires lots of typing of verbose (and ugly) code.
That verbosity tends to make any discussion of JNI equally verbose. We apologize
in advance for the apparent complexity of the discussion to follow.
When parameters are passed from Java to a native language, they are not
received as Java objects, nor are they received as objects or structures in the receiv-
ing native language. The former would be impossible, since a native language
has no facilities to deal with Java objects. The latter is somewhat conceivable for
an object-oriented native language such as C
,but is impossible for a general
JNI design that supports non-object-oriented languages such as C or assembly
language. There are two key things to remember throughout the discussion to
follow:
Java objects passed to a native language are not received as normal objects or structures
in that language but rather as some intermediate data types.
There are special JNI functions provided to access fields within those intermediate types
and even to convert some intermediate types to native data types.
++
Because of this need to convert to and from the intermediate data types, the code
growsverbose (and ugly).
22.4.1 The Java interface pointer
The access and conversion functions are provided in the JNI library itself.
There are many JNI functions - FindClass() , GetMethodID() , CallInt-
Method() , CallStaticFloatMethod() ,toname just a few. These are C
and C
functions , not Java methods. The function naming convention does not
use the standard Java method naming convention of initial lower case, but rather
uses an initial upper case letter.
++
Search WWH ::




Custom Search