* JNI
* 本地方法使用native进行声明,一般使用C语言编写
* 示例:
public class NativeDemo {
int i;
public static void main(String args[]) {
NativeDemo ob = new NativeDemo();
ob.i = 10;
System.out.println("This is ob.i before the native method:" +
ob.i);
ob.test();
System.out.println("This is ob.i after the native method:" +
ob.i);
}
public native void test();
static {
System.loadLibrary("NativeDemo");
}
}
* 编译代码,得到NativeDemo.class,然后使用javah.exe生成文件NativeDemo.h。
* 在test()方法实现中将包含NativeDemo.h
* 为了生成NativeDemo.h,使用命令:javah -jni NativeDemo,生成的文件如下:
#include <jni.h>
#ifndef _Included_NativeDemo
#define _Included_NativeDemo
#ifdef _ _cplusplus
extern "C" {
#endif
JNIEXPORT void JNICALL Java_NativeDemo_test
(JNIEnv *, jobject);
#ifdef _ _cplusplus
}
#endif
#endif
* 编写test()方法的实现代码,NativeDemo.c文件:
#include <jni.h>
#include "NativeDemo.h"
#include <stdio.h>
JNIEXPORT void JNICALL Java_NativeDemo_test(JNIEnv *env, jobject obj)
{
jclass cls;
jfieldID fid;
jint i;
printf("Starting the native method.\n");
cls = (*env)->GetObjectClass(env, obj);
fid = (*env)->GetFieldID(env, cls, "i", "I");
if(fid == 0) {
printf("Could not get field id.\n");
return;
}
i = (*env)->GetIntField(env, obj, fid);
printf("i = %d\n", i);
(*env)->SetIntField(env, obj, fid, 2*i);
printf("Ending the native method.\n");
}
* 进行编译并创建dll。通过c/c++编译器:
Cl /LD NativeDemo.c