Sunday, October 10, 2010

Java Native Interface

Java Native Interface or JNI is used to define methods in java which will be implemented in C/C++ code. This is very useful to implement some low level functionality which are not supported by Java.
For an example consider that we are creating a java project named “HelloWorldJNI” which has the following structure and location. 
Class Name: HelloWorldJNI
Structure:
HelloWorldJNI
\src
\bin
.settings
.classpath
.project

Package:
test.HelloWorld
Location:
C:\workspace\HelloWorldJNI

Steps in the JNI programming

Step #1: JNI requires the native methods to be declared in java as,
public class HelloWorld{
       public native void displayHelloWorld();
       static{
             System.loadLibrary("HelloWorldDLL");
       }

}
Step #2: compile the class using jdk’s javac compiler as follows,
C:\workspace\HelloWorldJNI>javac.exe src\test\HelloWorld.java
Step #3: Using jdk’s javah.exe create the header file in C/C++ code by invoking following command from the command prompt.
C:\workspace\HelloWorldJNI>javah -jni -o src\test\HelloWorld.h -classpath C:\workspace\HelloWorldJNI\src test.HelloWorldhere “–o” will define the output file name where “–classpath” will define the working path and “test.HelloWorld” will give the input file name.
Step #4: create a Win32 DLL in C/C++ named HelloWorldDLL and copy the DLL file to the C:\workspace\HelloWorldJNI\src location.
Step #5: create a main method in test.TestApp class in java as follows,
public class TestApp{
     public static vois main(String[] arg){
          HelloWorld hd = new HelloWorld();
          hd.displayHelloWorld();
     }
}
Step #6: in the command prompt run the program as
C:\workspace\HelloWorldJNI>java HelloWorldJNI
This entire process is illustrated in the following diagram which was taken from the The JNI Programmer’s Guide. Finally the result will be displayed in the command prompt as “Hello World!” as shown in the below diagram.

A complete JNI learning experience can be gained through going through The Java Native Interface Programmer’s Guide and Specification. Hope this article helped you to do a simple Hello World application correctly which has a packaging structure.


No comments:

Post a Comment