public class TestJNI {
// 定义 native 方法
private native void say();
static {
// 加载动态库
// 从当前路径或 java.library.path 查找, 去掉文件扩展名, macos 需要去掉 lib 前缀
System.loadLibrary("TestJNI");
// 或者使用文件绝对路径加载
// System.load( "/path/to/TestJNI.so");
}
public static void main(String[] args) {
new TestJNI().say();
}
}
javah TestJNI
修改 TestJNI.h
中 #include <jni.h>
-> #include "jni.h"
这样会优先从当前目录寻找 jni.h
头文件
#include "TestJNI.h"
JNIEXPORT void JNICALL Java_TestJNI_say (JNIEnv *env, jobject obj) {
printf("hello world");
}
-
拷贝依赖的 JNI 相关头文件到当前目录, 或者使用 gcc 编译时指定参数
-I $JAVA_HOME/include -I $JAVA_HOME/include/darwin
cp $JAVA_HOME/include/jni.h . cp $JAVA_HOME/include/darwin/jni_md.h .
-
编译
- Linux
gcc -shared TestJNI.cpp -o TestJNI.so
- MacOS
gcc -dynamiclib TestJNI.cpp -o libTestJNI.dylib
- Windows
gcc -shared TestJNI.cpp -o TestJNI.dll
javac TestJNI.java
java TestJNI
如何查看 java.library.path
地址
public class PrintJavaLibPath {
public static void main(String[] args) {
String[] split = System.getProperty("java.library.path").split(":");
for (String string : split) {
System.out.println(string);
}
}
}