Java Programming/Java Native Interface

The Java Native Interface (JNI) enables Java code running in a Java Virtual Machine (JVM) to call and to be called by native applications (programs specific to a hardware and operating system platform) and libraries written in other languages, such as C, C++ and assembly.

JNI can be used:


 * To implement or use features that are platform-specific.
 * To implement or use features that the standard Java class library does not support.
 * To enable an existing application&mdash;written in another programming language&mdash;to be accessible to Java applications.
 * To let a native method use Java objects in the same way that Java code uses these objects (a native method can create Java objects and then inspect and use these objects to perform its tasks).
 * To let a native method inspect and use objects created by Java application code.
 * For time-critical calculations or operations like solving complicated mathematical equations (native code may be faster than JVM code).

On the other hand, an application that relies on JNI loses the platform portability Java offers. So you will have to write a separate implementation of JNI code for each platform and have Java detect the operating system and load the correct one at runtime. Many of the standard library classes depend on JNI to provide functionality to the developer and the user (file I/O, sound capabilities...). Including performance- and platform-sensitive API implementations in the standard library allows all Java applications to access this functionality in a safe and platform-independent manner. Only applications and signed applets can invoke JNI. JNI should be used with caution. Subtle errors in the use of JNI can destabilize the entire JVM in ways that are very difficult to reproduce and debug. Error checking is a must or it has the potential to crash the JNI side and the JVM.

This page will only explain how to call native code from JVM, not how to call JVM from native code.

Calling native code from JVM
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  pointer, a   pointer, and any Java arguments declared by the Java method. A JNI function may look like this: The   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, albeit with considerably less ease.

On Linux and Solaris platforms, if the native code registers itself as a signal handler, it could intercept signals intended for the JVM. Signal chaining should be used to allow native code to better interoperate with JVM. On Windows platforms, Structured Exception Handling (SEH) may be employed to wrap native code in SEH try/catch blocks so as to capture machine (CPU/FPU) generated software interrupts (such as NULL pointer access violations and divide-by-zero operations), and to handle these situations before the interrupt is propagated back up into the JVM (i.e. Java side code), in all likelihood resulting in an unhandled exception.

C++ code
For example, the following converts a Java string to a native string: The JNI framework does not provide any automatic garbage collection for non-JVM memory resources allocated by code executing on the native side. Consequently, native side code (such as C, C++, or assembly language) must assume the responsibility for explicitly releasing any such memory resources that it itself acquires.

C code
Note that C++ JNI code is syntactically slightly cleaner than C JNI code because like Java, C++ uses object method invocation semantics. That means that in C, the  parameter is dereferenced using   and   has to be explicitly passed to   methods. In C++, the  parameter is dereferenced using   and the   parameter is implicitly passed as part of the object method invocation semantics.

Objective-C code
JNI also allows direct access to assembly code, without even going through a C bridge.

Mapping types
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. The following table shows the mapping of types between Java (JNI) and native code.

In addition, the signature  would mean the class uniquely specified by that name; e.g., the signature   refers to the class. Also, prefixing  to the signature makes the array of that type; for example,   means the int array type. Finally, a  signature uses the   code. Here, these types are interchangeable. You can use  where you normally use an , and vice-versa, without any typecasting required.

However, mapping between Java Strings and arrays to native strings and arrays is different. If you use a  in where a   would be, your code could crash the JVM.

The encoding used for the,  ,  ,  ,   functions is not standard UTF-8, but modified UTF-8. The null character (U+0000) and codepoints greater than or equal to U+10000 are encoded differently in modified UTF-8. Many programs actually use these functions incorrectly and treat the UTF-8 strings returned or passed into the functions as standard UTF-8 strings instead of modified UTF-8 strings. Programs should use the,  ,  ,  ,  ,  , and   functions, which use UTF-16LE encoding on little-endian architectures and UTF-16BE on big-endian architectures, and then use a UTF-16 to standard UTF-8 conversion routine.

The code is similar with Java arrays, as illustrated in the example below that takes the sum of all the elements in an array.

Of course, there is much more to it than this.

JNIEnv*
A JNI environment pointer is passed as an argument for each native function mapped to a Java method, allowing for interaction with the JNI environment within the native method. This JNI interface pointer can be stored, but remains valid only in the current thread. Other threads must first call  to attach themselves to the VM and obtain a JNI interface pointer. Once attached, a native thread works like a regular Java thread running within a native method. The native thread remains attached to the VM until it calls  to detach itself.

To attach to the current thread and get a JNI interface pointer: JNIEnv *env; (*g_vm)->AttachCurrentThread (g_vm, (void **) &env, NULL);

To detach from the current thread: (*g_vm)->DetachCurrentThread (g_vm);

HelloWorld
HelloWorld.h

libHelloWorld.c

make.sh

Advanced uses
Not only can native code interface with Java, it can also draw on a, which is possible with the Java AWT Native Interface. The process is almost the same, with just a few changes. The Java AWT Native Interface is only available since J2SE 1.3.