Incorporating native code (C/C++)
by , 11-12-2011 at 05:42 PM (660 Views)
JNI (Java Native Interface) is a powerful feature that provides the developers to call legacy code written in C/C++ and Java. In the post, I will briefly introduce how JNI helps us in doing so.
First step is to create a Java class that declares native method. Native method’s signature contains keyword native and it indicates that this method is implemented in another language. Native method declaration is terminated with a semicolon. Also note that native method does not contain implementation.
Private native void print();
Implementation of print() method will be in a C file.
Next step is to load the library that contains the implementation of the native method. Native library is loaded using static initializer. JVM is responsible for loading the library in static initializer before calling the native method.
Next step is to simply compile the class and generate the class file. We now need to generate a header file using javah tool.Java Code:static { System.loasLibrary("HelloWorld"); }
javah -jni HeloWorld
Header file will contain function prototype with following signature
JNIEXPORT void JNICALL
Java_HelloWorld_print(JNIEnv *, jobject);
No need to go into details here. just note the signature. Now open the C file and include the .h file in it.
#include "HelloWorld.h";
JNIEXPORT void JNICALL
Java_HelloWorld_print(JNIEnv *, jobject)
{
...
}
So we implemented the native method in C. Now simply compile the C file and generate dll for it which will be the native library. All is set now. Run the java program.
I hope you now have the basic idea about JNI. Dig deep and explore as required.









Email Blog Entry
License4J 4.0
05-22-2013, 12:23 AM in Java Software