JNI (Java Native Interface) is used to call C/C++ libraries by Java code.

The C/C++ library is known as SO library in Linux and is known as DLL in windows.

Environment Requirment
  • Linux
  • GCC
  • G++
  • Java 1.8+

If you have not prepared for the environment, you can install them by commands below:

yum -y install gcc
yum -y install gcc+ gcc-c++
yum -y install java-1.8.0-openjdk-devel.x86_64
Let’s Start

First, I prepared a Java file called JniDemo.java and its content is below:

[root@snail jni_helloworld]# cat JniDemo.java 
public class JniDemo{

  public static void main(String[] args){
    System.out.println("Hello, I'm Java!");
    new JniDemo().hello();

  public native void hello(); // Native key word tell Jvm that the method is from SO libraries instead of Java.

    System.loadLibrary("cpp_lib_demo"); // Loading the C library.

Second, use javah tool to generate JniDemo.h file.

[root@snail jni_helloworld]# javah JniDemo
[root@snail jni_helloworld]# ls
JniDemo.h  JniDemo.java

Third, It’s time to code our cpp file.

[root@snail jni_helloworld]# cat cpp_demo.cpp 
#include "JniDemo.h" // Import generated header file.
#include "jni.h"
JNIEXPORT void JNICALL Java_JniDemo_hello
  (JNIEnv * env, jobject jb){
      printf("%s","Hello, I'm Cpp.\n");

To compile our cpp file, we need to make our Makefile file.

[root@ jni_helloworld]# cat Makefile 
libcpp_lib_demo.so : cpp_demo.cpp
	g++ -o $@ $+ -fPIC -shared -I/usr/lib/jvm/java-1.8.0-openjdk- -I/usr/lib/jvm/java-1.8.0-openjdk-

.PHONY : clean
clean :
	rm libcpp_lib_demo.so

Note: You need to modify the java path to your java path.

And now, let’s us to compile our Java file to class and compile our cpp file to SO library.

 [root@snail jni_helloworld]# javac JniDemo.java 
 [root@snail jni_helloworld]# make
g++ -o libcpp_lib_demo.so cpp_demo.cpp -fPIC -shared -I/usr/lib/jvm/java-1.8.0-openjdk- -I/usr/lib/jvm/java-1.8.0-openjdk-
 [root@snail jni_helloworld]# ls
cpp_demo.cpp  JniDemo.class  JniDemo.h  JniDemo.java  libcpp_lib_demo.so  Makefile

Now, we can run our JNI program.

[root@snail jni_helloworld]# java -Djava.library.path='.' JniDemo
Hello, I'm Java!
Hello, I'm Cpp.