Java Reference
In-Depth Information
for their platform in order for the implementation to be J2SE compliant. So a
developer can be sure that any compliant J2SE implementation on any platform
will include the required JNI libraries for C and C
.
This chapter explains how JNI is used to call C and C
++
++
code. The examples
given are necessarily simple and somewhat contrived since it is not the purpose
of this topic to describe C/C
++
boilerplate code to produce working examples. (See references [2,3] for additional
examples.)
JNI is often thought of as complicated and difficult. Actually, “verbose” is
a more apt description of JNI. While it can be argued that JNI code is “ugly,”
which makes it appear complicated, the concepts are straightforward, not difficult.
Much of the ugliness can be attributed to the fact that JNI is designed to be general
enough to work with almost any native language. It is possible, at least in concept,
that some vendor could implement JNI libraries for languages other than C and
C
++
programming, but we provide enough C/C
,say Smalltalk or Fortran. To our knowledge, no vendor has done so. To
gain access to codes written in Fortran, for example, one must use a C or C
++
++
layer as an intermediary. Such C or C
code is often called glue code since it is
the “glue” that holds the Java and Fortran code together. While calling any native
code from Java using JNI is always done the same way, there is no such standard
for calling Fortran from C/C
++
++
. Therefore, we do not address here how to write
such glue code.
A JNI native method written in C/C
has full access to Java objects, although
the way in which those objects are accessed and modified is necessarily different
than how they are used in the Java language. Native methods can obviously call
other methods written in that native language and can use any other feature that
is available in that language. What may not be so obvious is that native methods
can also call Java methods, including standard Java API methods or methods that
are part of a custom written Java class. Native methods can create Java objects,
including arrays. Native methods can cause Java classes to be loaded and can
discover and gain access to fields and methods in those classes. Native methods
can throw Java exceptions that can be caught in the Java code. The rest of this
chapter describes how to use JNI to take advantage of all these features and
more.
While JNI is most often used to call from Java into a native language, it is even
possible for a regular non-Java program running on the native operating system
to invoke a JVM to gain access to Java classes and features. This use of JNI is
referred to as the Invocation API, but we do not discuss it further.
++
22.3 Hello World in JNI
We begin our study of JNI with a simple example that calls a native method that
prints Hello World on the console. We first write the Java program that
Search WWH ::




Custom Search