JNI (Java Native Interface)
JNI is Sun's standard programming interface for calling "native
methods" (compiled, platform-specific, object code) from Java
applications, and for embedding and calling the Java Virtual Machine from
native applications. The primary goal is binary compatibility of
native method libraries across all Java Virtual Machine implementations
on a given platform.
By programming to the JNI, you can:
- Call non-Java object modules
- Pass and return primitive and user-defined data types
- Throw and catch exceptions
- Pass Java objects and invoke methods on those objects
- Load Java classes and obtain class information
You can also use the JNI with the Invocation API to enable an arbitrary
native application to embed the Java VM. This allows programmers to
easily make their existing applications Java-enabled without having to
link with the JVM source code.
JNI should not be confused with other competing "native method" APIs:
- JDK 1.0's NMI (Native Method Interface)
- Netscape's JRI (Java Runtime Interface )
[http://www17.netscape.com/eng/jri/jri-intro.html]
- Microsoft's RNI (Raw Native Interface)
These other APIs do not offer the future and/or the portability
guaranteed by Sun's official JNI. Native method programmers should
program to Sun's JNI. This insulates the code from unknowns, such as
the JVM implementation that the end user is running, and, provides the
assurance of active support (or a migration path) in the future. By
conforming to the JNI standard, the native method library produced will
have the best chance of running in any Java VM - now, and in the
future.
This chapter will demonstrate JNI's C binding. "You can also use
C++ instead of C to write native methods. There are a few advantages -
type checking is slightly stricter, and accessing the JNI functions is
a bit more convenient. However, JNI does not support any direct
correspondence between classes in Java and C++. Even when programming
with C++, you must access the fields and methods of Java classes through
C function calls." [Horstmann98, p581]
There are several implementation possibilities not covered in this chapter:
accessing Java static members, mapping Java
native methods to C++ member functions, passing array arguments,
the va_list type, and throwing exceptions from Java to C++.