View RSS Feed

My Java Tips

Incorporating native code (C/C++)

Rate this Entry
by , 11-12-2011 at 06:42 PM (1528 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.

Java Code:
static {
Next step is to simply compile the class and generate the class file. We now need to generate a header file using javah tool.

javah -jni HeloWorld

Header file will contain function prototype with following signature

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";

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.

Submit "Incorporating native code (C/C++)" to Facebook Submit "Incorporating native code (C/C++)" to Digg Submit "Incorporating native code (C/C++)" to Submit "Incorporating native code (C/C++)" to StumbleUpon Submit "Incorporating native code (C/C++)" to Google

Java SE