您好,登錄后才能下訂單哦!
可以將native方法比作Java程序同C程序的接口,其實現步驟為:
1、編寫java源程序,add用native修飾
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 <jni.h>
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 <stdio.h>
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
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。