JNI Demo In Linux

Overview

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.

  static{
    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-1.8.0.292.b10-1.el7_9.x86_64/include -I/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.292.b10-1.el7_9.x86_64/include/linux

.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-1.8.0.292.b10-1.el7_9.x86_64/include -I/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.292.b10-1.el7_9.x86_64/include/linux
 [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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

iioSnail

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值