Monday, August 13, 2007

How to write a JNI code and invoke the same from a Java class?

JNI - Java Native Interface.
JNI provides a mapping for both C and C++ by default.

How to write a JNI code and invoke the same from a Java class?

1) Native Method Declaration
The native declaration provides the bridge to run the native function in the Java1 virtual machine. In this example, the loadFile function maps onto a C function called Java_ReadFile_loadFile. The function implementation accepts a String that represents a file name and returns the contents of that file in the byte array.
native byte[] loadFile(String name);

2) Load the Library
The library containing the native code implementation is loaded by a call to System.loadLibrary().

3) Compile the Program
To compile the program, just run the javac compiler command as you normally would:
javac ReadFile.java

4) Generate the Header File
To generate a a header file, run the javah command on the ReadFile class. In this example, the generated header file is named ReadFile.h. It provides a method signature that you have to use when you implement the loadfile native function.
javah -jni ReadFile

5) Implement the Native Method
In this native C source file, the loadFile definition is a copy and paste of the C declaration contained in ReadFile.h.

6) Compile the Dynamic or Shared Object Library
The library needs to be compiled as a dynamic or shared object library so it can be loaded at runtime. Static or archive libraries are compiled into an executable and cannot be loaded at runtime.

To run, the Java virtual machine needs to be able to find the native library. To do this, set the library path to the current directory as follows:
Unix or Linux: LD_LIBRARY_PATH=`pwd` export LD_LIBRARY_PATH
Windows NT/2000/95: set PATH=%path%;.

Ref :
http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jniexamp.html

No comments: