Thursday 6 November 2014

JNI - Calling native functions in Java

This example has been taken from this link -  http://www.science.uva.nl/ict/ossdocs/java/tutorial/native1.1/stepbystep/index.html

Hello world example for native functions :

1.) Compile your Java code using javac.
/*-------------------------------------
Class HelloWorld
--------------------------------------*/
class HelloWorld {
    public native void displayHelloWorld();

    // Declare a native method average() that receives two ints and return a double containing the average
    public native double average(int n1, int n2);

    static {
        //System.loadLibrary("hello");
        // You can specify the full path to the lib file
    System.load("/Users/xyz/Documents/workspace/JNITest/src/libhello.so");
    }
}


/*-------------------------------------
Class JNITest - with main()
--------------------------------------*/
public class JNITest {
public static void main(String[] args) throws InterruptedException {
HelloWorld hw = new HelloWorld();
hw.displayHelloWorld();

Thread.sleep(1000);
System.out.println("Exiting ... "+hw.average(2, 100));
}

}

2.) Generate the c++ header file using the javah command

> javah HelloWorld

3.) Write the c++ native function implementation

#include <jni.h>
#include "HelloWorld.h"
#include <stdio.h>

JNIEXPORT jdouble JNICALL Java_HelloWorld_average(JNIEnv * jenv, jobject jo, jint n1 , jint n2){

return ((jdouble)n1 + n2) / 2.0;
}

JNIEXPORT void JNICALL
Java_HelloWorld_displayHelloWorld(JNIEnv *env, jobject obj)
{
  printf("Hello world!\n");
  return;
}

4.) Compile your c++ code and create a shared library

Note: If you have problems importing <jni.h> on linux box ensure that the include path contains your java's include directories. For example:
g++ -O3 -shared -fPIC mibc.cpp -I /usr/java/default/include/ -I /usr/java/default/include/linux/ -o libhello.so -lrt

5.) Run your java program
Place your shared library in the correct path as specified in the java System.load() call. And run the java program using "java JNITest"

More Reading:
To use different data types for native calls -  https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html
JNI performance and overheads -
http://thinkingandcomputing.com/2014/03/30/eliminating-jni-overhead/
http://a-hackers-craic.blogspot.in/2012/03/jni-overheads.html
http://stackoverflow.com/questions/6175209/low-latency-ipc-between-c-and-java
http://stackoverflow.com/questions/7699020/what-makes-jni-calls-slow
http://www.ibm.com/developerworks/java/library/j-jni/
http://normanmaurer.me/blog/2014/01/07/JNI-Performance-Welcome-to-the-dark-side/
http://www.javaworld.com/article/2077554/learn-java/java-tip-54--returning-data-in-reference-arguments-via-jni.html
http://stackoverflow.com/questions/1632367/passing-pointers-between-c-and-java-through-jni

No comments:

Post a Comment