setTitle("The Native Add Result is "+String.valueOf(test.nadd(10, 20)));
28
29
}
30
31
}
32
33
Nadd.java
34
35
packagecom.hello.jnitest;
36
37
38
39
publicclassNadd {
40
41
static{
42
43
System.loadLibrary("hello_jni");
44
45
}
46
47
48
49
publicnativeintnadd(inta, intb);
50
51
}
Java代码说明: 1)jnitest.java是一个activity的类对象,在该类对象中生成调用JNI函数的类对象,同时调用JNI方法,最后将JNI方法的结果显示到标题栏上; 2)Nadd.java是一个引用和声明JNI库和函数的类,其中System.loadLibrary();函数用来引用JNI库,默认JNI库放在 android系统的/system/lib/目录下;public nadd int nadd(int a, int b);为声明需要在java程序中使用的JNI库中的函数; JNI中java部分的代码到此就结束了,总结一下在java代码中需要做两件事: 1)使用System.loadLibrary()函数来引用JNI库; 2)声明调用JNI库的函数且前面添加native关键字; android C/C++部分代码:
01
#define LOG_TAG "hello-JNI"
02
#include <stdio.h>
03
#include <stdlib.h>
04
#include <unistd.h>
05
#include <sys/types.h>
06
#include <sys/stat.h>
07
#include <fcntl.h>
08
#include <assert.h>
09
#include "jni.h"
10
#include "JNIHelp.h"
11
#include "android_runtime/AndroidRuntime.h"
12
staticjint com_hello_jnitest_jnitest_nadd(JNIEnv *env, jobject obj, jint a, jint b)