3種引用類型
類class
接口interface
數(shù)組array
基本數(shù)據(jù)類型的傳遞
第一步: 編寫java
public class HelloWorld{
Mclass mclass=new Mclass();
static {
System.loadLibrary("native");
}
public native String getString(String str);
public native int[] getArray(int[] arr);
public native void say(Minterface minter);
public native void classSay(Mclass mclass);
public static void main(String[] args) {
final HelloWorld world=new HelloWorld();
int[] arr={1,2,3,4,5,6};
System.out.println(world.getString("I AM CLASS"));
for (int mem : world.getArray(arr)) {
System.out.println(mem);
}
world.say(new Minterface(){
public void say(){
world.mclass.say();
}
});
world.classSay(world.mclass);
}
}
class Mclass{
public void say(){
System.out.println("I AM CLASS");
}
}
interface Minterface{
void say();
}
第二步: 編譯冰悠、獲取财忽,更改JNI頭文件名
$ javac HelloWorld.java
$ javah HelloWorld
$ mv HelloWorld.h HelloWorld.c
第三步完成JNI文件的編寫
#include <jni.h>
JNIEXPORT jstring JNICALL Java_HelloWorld_getString
(JNIEnv * env, jobject job, jstring jstr)
{
const char *str;
str=(*env)->GetStringUTFChars(env,jstr,NULL);
if (str==NULL)
{
return NULL;
}
printf("C received : %s\n", str);
return jstr;
}
JNIEXPORT jintArray JNICALL Java_HelloWorld_getArray
(JNIEnv * env, jobject job, jintArray arr){
jint *carr;
jint i= 0;
carr = (*env)->GetIntArrayElements(env, arr, NULL);
if (carr == NULL) {
return arr; /* exception occurred */
}
for (i=0; i<6; i++) {
printf("num : %d\n", i);
}
(*env)->ReleaseIntArrayElements(env, arr, carr, 0);
return arr;
}
JNIEXPORT void JNICALL Java_HelloWorld_say
(JNIEnv * env, jobject job, jobject pramjob){
printf("%s\n", "received an object! 1");
}
JNIEXPORT void JNICALL Java_HelloWorld_classSay
(JNIEnv * env, jobject job, jobject pramjob){
printf("%s\n", "received an object! 2");
}
第四步: 編譯胜榔、設(shè)置程序共享庫(kù)位置
$ gcc HelloWorld.c -shared -fPIC -o libnative.so -I /usr/lib/jvm/java-7-openjdk-amd64/include/
$ export LD_LIBRARY_PATH=.
第五步: 執(zhí)行鼠冕、打印成功灾前!
C received : I AM CLASS
I AM CLASS
num : 0
num : 1
num : 2
num : 3
num : 4
num : 5
1
2
3
4
5
6
received an object! 1
received an object! 2