java通过JNI接口调用C语言-初级

JNI(java native interface):即java本地调用C的接口。

先看整体运行:

 

下面是过程:

#vim test.java

 1 public class test{
 2     
 3     public native static int add(int a, int b);  //指明本地函数
 4     static{
 5         System.loadLibrary("add");               //指定动态库
 6     };
 7     
 8     public static void main(String args[]){
 9         
10         int ret = 0;
11 
12         ret = add(6, 8);
13     
14         System.out.println("hello world! " + ret + "\n");
15     }
16 };

既然指定了动态库,那么这个库从何而来?对新手来说使用javah 这个命令就可以了,根据这个命令生成的头文件生成库。

#javac test.java

#javah -jni test

此时生成了test.h文件,修改如下:

#vim test.h

1 #include <jni.h>
2 jint Java_test_add (JNIEnv *env, jclass obj, jint a, jint b)
3 {
4     return a + b;
5 }

把这个头文件变成.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         //指定库的路径为本目录

 

posted @ 2014-12-29 22:44  Qt小罗  阅读(2560)  评论(0编辑  收藏  举报