Java语言和C语言混合编程(1)--Javanative关键字

可以将native方法比作Java程序同C程序的接口,其实现步骤为:
1、编写java源程序,add用native修饰

创新互联主营锡山网站建设的网络公司,主营网站建设方案,重庆APP开发,锡山h5重庆小程序开发公司搭建,锡山网站营销推广欢迎锡山等地区企业咨询

package p2019.p06;

public class NativeAdd {
    public native int add(int a,int b);
}

2、编译java程序,生成NativeAdd.class文件
[root@localhost java]# javac p2019/p06/NativeAdd.java
生成NativeAdd.class NativeAdd.java
3、javah生成.h文件
[root@localhost java]# javah p2019.p06.NativeAdd
生成p2019_p06_NativeAdd.h

    1 /* DO NOT EDIT THIS FILE - it is machine generated */
    2 #include 
    3 /* Header for class p2019_p06_NativeAdd */
    4 
    5 #ifndef _Included_p2019_p06_NativeAdd
    6 #define _Included_p2019_p06_NativeAdd
    7 #ifdef __cplusplus
    8 extern "C" {
    9 #endif
 10 /*
 11  * Class:     p2019_p06_NativeAdd
 12  * Method:    add
 13  * Signature: (II)I
 14  */
 15 JNIEXPORT jint JNICALL Java_p2019_p06_NativeAdd_add
 16   (JNIEnv *, jobject, jint, jint);
 17 
 18 #ifdef __cplusplus
 19 }
 20 #endif
 21 #endif

4、将生成的.h文件拷贝到/usr/java/jdk1.8.0_181-amd64/include/和/usr/java/jdk1.8.0_181-amd64/include/llinux目录下,编译C程序时用
5、编写C程序NativeAdd.c

        1 #include 
  2 #include "p2019_p06_NativeAdd.h"
  3 JNIEXPORT jint JNICALL Java_p2019_p06_NativeAdd_add(JNIEnv * _env, jobject _obj, jint _a, jint _b)
  4 {
  5     return _a+_b;
  6 }

6、编译C程序,生成.so文件
gcc -I /usr/java/jdk1.8.0_181-amd64/include/ -I /usr/java/jdk1.8.0_181-amd64/include/linux/ NativeAdd.c -fPIC -shared -LD -o NativeAdd.so
7、编写java测试程序,调用NativeAdd.so

package p2019.p06;

public class NativeAddTest {
    public static void main(String[] args){
        System.out.println(System.getProperty("java.library.path"));
//      System.loadLibrary("NativeAdd");这个方法找不到NativeAdd.so
        System.load("/usr/lib/NativeAdd.so");
        NativeAdd nativeAdd = new NativeAdd();
        System.out.println(nativeAdd.add(1,2));
    }
}

显示结果 3


网页题目:Java语言和C语言混合编程(1)--Javanative关键字
文章网址:http://myzitong.com/article/igodgo.html