Home » Android » NDK / Middleware / HAL » Java Native Interface ( JNI ) Example , Calling Native C functions from JAVA

Java Native Interface ( JNI ) Example , Calling Native C functions from JAVA

The Java Native Interface (JNI) establishes a well-defined and platform-independent interface between the JAVA and Native C program / library. Using JNI we can access the native C API’s from JAVA applications.


pre-requisite – Install JAVA using “How to Install Java using apt-get command on Ubuntu ?”


Write a JAVA class [ HelloWorld.java ]

public class HelloWorld { 

static { 
    System.loadLibrary("hello"); 
} 

public native void printHelloWorld();

}


Compile the class using javac

$ javac HelloWorld.java

after this HelloWorld.class file should get created.


Create header file required for writing a native program

$ javah -jni HelloWorld

Above command will create a C header file HelloWorld.h

Write a helloworld.c native c program.

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

JNIEXPORT void JNICALL Java_HelloWorld_printHelloWorld (JNIEnv *env, jobject obj) { 
        printf("Hello World\n");
}      


Create a shared library.

$ gcc -I/usr/lib/jvm/java-11-openjdk-amd64/include/ -I/usr/lib/jvm/java-11-openjdk-amd64/include/linux/ -shared -o libhello.so helloworld.c

We need to add include paths “usr/lib/jvm/java-11-openjdk-amd64/include/” and “/usr/lib/jvm/java-11-openjdk-amd64/include/linux/” for the jni.h and jni_md.h headers respectively.

Write a Main java class[ Main.java ], which will call native function.

public class Main {

        public static void main(String[] args) {
                new HelloWorld().printHelloWorld();
        }

}      


Compile Main.java

$ javac Main.java

Now set the LD_LIBRARY_PATH so that the C shared library can be found by the JAVA executable as,

$ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$PWD

Run the program

$ java Main

Reference’s
1) JNI Example
2) http://java.sun.com/docs/books/jni/html/start.html

1 thought on “Java Native Interface ( JNI ) Example , Calling Native C functions from JAVA”

Leave a Comment