JNI (Java Native Interface) allows implementing methods in C/C++, and use them in Java.
I use hombrew install java, java version is java 10.
$ java --version
java 10.0.2 2018-07-17
Java(TM) SE Runtime Environment 18.3 (build 10.0.2+13)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.2+13, mixed mode)class JNIExample {
// Native method, no body.
public native void sayHello(int length);
public static void main (String args[]) {
String str = "Hello, world!";
(new JNIExample()).sayHello(str.length());
}
// This loads the library at runtime. NOTICE: on *nix/Mac the extension of the
// lib should exactly be `.jnilib`, not `.so`, and have `lib` prefix, i.e.
// the library file should be `libjniexample.jnilib`.
static {
System.loadLibrary("jniexample");
}
}This gives you JNIExample.class:
javac JNIExample.javajavac -h ./ JNIExampleNOTICE: Java 10 removed javah, we can use javac generate header
file.
javah -jni JNIExample # java 8This gives you JNIExample.h (do not edit it manually!):
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class JNIExample */
#ifndef _Included_JNIExample
#define _Included_JNIExample
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: JNIExample
* Method: sayHello
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_JNIExample_sayHello
(JNIEnv *, jobject, jint);
#ifdef __cplusplus
}
#endif
#endifNative implementation:
#include <stdio.h>
#include <jni.h>
#include "JNIExample.h"
JNIEXPORT void JNICALL Java_JNIExample_sayHello
(JNIEnv *env, jobject object, jint len) {
printf("\nThe length of your string is %d.\n\n", len);
}IMPORTANT: library extension should exactly be .jnilib (not
.so!), and should have lib prefix, i.e. libjniexample.jnilib:
gcc -I"$JAVA_HOME/include" -I"$JAVA_HOME/include/darwin/" -o libjniexample.jnilib -shared JNIExample.cNOTICE: must set $JAVA_HOME :
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-10.0.2.jdk/Contents/HomeNotice, we set java.library.path to current directory, where the
libjniexample.jnilib was compiled to:
java -Djava.library.path=. JNIExampleResult:
The length of your string is 13.