Using The Java Native Interface

In this tutorial we illustrate how the Java Native Interface (JNI) can be used to permit Java programs to communicate with C programs. We begin by compiling the Java program and the C program at the command prompt (i.e. outside of Eclipse) using the MinGW gcc compiler. Once the programs are compiled and executing correctly, we show how the programs can be integrated into an Eclipse project using the CDT plugin.

The essential idea behind the JNI is that in Java we sometimes want to access functionality that is unavailable to us through the standard Java class libraries. The functionality may be native to the particular operating system we are using, we might want to avoid re-writing pre-existing libraries that are written in a different language, or we may want to use C to optimize certain slow areas of the code.

Whatever the reason for using it, the JNI bridges the gap between Java and C. It does this by accessing shared libraries that can be written in C (or possibly C++). We first write our Java code, identifying certain methods as belong to such a library. Then we write our C code and compile it into a library. We can then run our Java code as usual, and it will transparently access the library and run the native function. It is important to remember that when we use the JNI, we lose many of the benefits that Java normally provides. In particular, C does not provide automatic garbage collection so extra caution is required to avoid introducing memory leaks.

Get pdf download Using The Java Native Interface

Related Tutorial

Tags: , , , , , , , , , , , , , , , , ,

Comments

Leave a Reply