JNI(java native interface):即java本地调用C的接口。
先看整体运行:
下面是过程:
#vim test.java
public class test{ public native static int add(int a, int b); //指明本地函数
static{
System.loadLibrary("add"); //指定动态库
}; public static void main(String args[]){ int ret = ; ret = add(, ); System.out.println("hello world! " + ret + "\n");
}
};
既然指定了动态库,那么这个库从何而来?对新手来说使用javah 这个命令就可以了,根据这个命令生成的头文件生成库。
#javac test.java
#javah -jni test
此时生成了test.h文件,修改如下:
#vim test.h
#include <jni.h>
jint Java_test_add (JNIEnv *env, jclass obj, jint a, jint b)
{
return a + b;
}
把这个头文件变成.c文件,不解释;注意:头文件没有的需要指定路径,我这里之前已经配置好了的。
#mv test.h test.c
下面开始生成动态库:
#gcc -c -fPIC test.c -o test.o //-fPIC指定与位置无关
#gcc -shared test.o -o libadd.so //链接生成动态库
最后执行java:
#LD_LIBRARY_PATH=. java test //指定库的路径为本目录