JNI (Java Native Interface,Java本地接口)是一种编程框架,使得Java虚拟机中的Java程序可以调用本地应用/或库,也可以被其他程序调用。 本地程序一般是用其它语言(C、C++或汇编语言等)编写的,并且被编译为基于本机硬件和操作系统的程序。
Java类
package cn.har01d.demo;
public class HelloNative {
static {
//System.load("/home/harold/workspace/JavaPractise/JavaNative/src/main/java/libHelloNative.so");
System.loadLibrary("HelloNative");
}
public static void main(String[] args) {
HelloNative.greeting("World");
HelloNative.greeting("Harold");
}
public static native void greeting(String name);
}
生成头文件
javah -classpath . -jni cn.har01d.demo.HelloNative
生成文件:cn_har01d_demo_HelloNative.h
文件内容:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class cn_har01d_demo_HelloNative */
#ifndef _Included_cn_har01d_demo_HelloNative
#define _Included_cn_har01d_demo_HelloNative
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: cn_har01d_demo_HelloNative
* Method: greeting
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_cn_har01d_demo_HelloNative_greeting
(JNIEnv *, jclass, jstring);
#ifdef __cplusplus
}
#endif
#endif
C语言实现功能
#include "cn_har01d_demo_HelloNative.h"
#include <stdio.h>
// g++ -fPIC -I ${JAVA_HOME}/include/ -I ${JAVA_HOME}/include/linux/ -shared -o libHelloNative.so cn_har01d_demo_HelloNative.c
JNIEXPORT void JNICALL Java_cn_har01d_demo_HelloNative_greeting(JNIEnv *env, jclass cl, jstring name) {
const char *nativeString = env->GetStringUTFChars(name, NULL);
printf("Hello %s!\n", nativeString);
env->ReleaseStringUTFChars(name, nativeString);
}
编译动态库
g++ -fPIC -I ${JAVA_HOME}/include/ -I ${JAVA_HOME}/include/linux/ -shared -o libHelloNative.so cn_har01d_demo_HelloNative.c
编译Java类
javac HelloNative.java
运行Java程序
java -cp . -Djava.library.path=. cn.har01d.demo.HelloNative
可以将动态库拷贝到java.library.path,比如:/usr/lib、/lib
然后直接运行:
java -cp . cn.har01d.demo.HelloNative
快捷脚本
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:.
echo "---编译动态库---"
g++ -fPIC -I ${JAVA_HOME}/include/ -I ${JAVA_HOME}/include/linux/ -shared -o libHelloNative.so cn_har01d_demo_HelloNative.c
cd cn/har01d/demo || exit
echo "---编译Java类---"
javac HelloNative.java
cd ../../../
echo "---运行Java程序---"
java -cp . cn.har01d.demo.HelloNative