The Java Native Interface (JNI) is a native programming interface in JDK. It is used to call C/C++ libraries from the libraries written in Java and vice-versa. This is a java API which bridges the gap between C/C++ and Java.
Why do we use Java Native Interface(JNI)?
JNI calls are used when we already have a library which is written in C/C++ language and we need to use that library in our Java application. For example, most of the drivers are programmed in C/C++ language, but since our application demands for JVM, so we can not directly use C/C++ code into java. We need an interface for this and which Java Native Interface(JNI) provides.
Requirements for making JNI calls:
In order to make JNI calls, the following tools must be installed on the system:
1) A Java Development Kit,
2) C/C++ compiler
The code process:
STEP 1 : Write a Java class
class HelloWorld
{
public native void sayHi(String name);
static
{
System.loadLibrary("nativelib");
}
public static void main(String[] args)
{
HelloWorld h = new HelloWorld();
h.sayHi("JNI");
}
}
STEP 2: Compile and Generate header files
To compile above code, the following command is used.
javac HelloWorld.java
Now, the code has been compiled and but it still lack the missing links for the native methods. For this run the following command
javah -jni HelloWorld
A header file will generated which would be used as a bridge betweed Java and Native methods. This file has auto generated contents and it is recommended not to change its contents.
STEP 3: Create C library implementation
#include "HelloWorld.h"
#include<string.h>
#include<stdio.h>
JNIEXPORT void JNICALL Java_HelloWorld_sayHi
(JNIEnv *env, jobject obj, jstring string) {
const char *str = (*env)->GetStringUTFChars(env, string, 0);
char cap[128];
strcpy(cap, str);
printf(“Hello %s”, str);
(*env)->ReleaseStringUTFChars(env, string, str);
}
STEP 4: Compile the native code
After coding in C language, we need to compile it. For this we use gcc compiler. The command to compile C code is somehow tricky, as follows:
gcc -fPIC -shared -I /usr/lib/jdk1.8.0_45/include/linux -I usr/lib/java1.8.0_45/include/ HelloWorld.c -o nativelib.so
The parameter :
-fPIC means that the generated output file is a Position Independent Code.
-shared means that it has to be shared with some other application.
-I asks for the path where the header file for Java Native Interface(JNI) implementation which is located in JAVA sdk path.
-o specifies the name of output native library file.
STEP 5: Running the application
java -Djava.library.path=. HelloWorld
1 thought on “Introduction to JNI- Java Native Interface2 min read”
Comments are closed.