JNI是Java Native Interface的缩写,通过使用native方法,Java可以调用本地C/C++子程序。声明一个本地子程序的方法是:在方法名前添加native修饰,如
public native void myfun();
调用该子程序的方法为:
static{
System.loadLibrary("myfun");
}
在Windows上,上面的myfun即指包含用C/C++写的myfun()的实体的DLL——myfun.dll。下面以NativeDemo程序为例来说明怎样在Windows下(XP+VS2008+JDK1.6u17)使用JNI。
1. 编写源程序NativeDemo.java
NativeDemo.java中声明了一个本地子程序test():
public native void test();
该子程序从主程序获得int变量i的值,对其加倍,然后返回给主程序。具体代码如下:
// Using Native method
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(); //call a native method
System.out.println("This is ob.i after the Native method: "+ob.i);
ob.test(); //call a native method
System.out.println("This is ob.i after the Native method: "+ob.i);
}
// declare native method
public native void test();
static{
// load DLL that contains static method
System.loadLibrary("NativeDemo");
}
}
2. 编译NativeDemo.java
javac NativeDemo.java
得到NativeDemo.class
3. 使用javah.exe生成NativeDemo.h
javah -jni NativeDemo
javah.exe在%JAVA_HOME%/bin下,生成的NativeDemo.h如下:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class NativeDemo */
#ifndef _Included_NativeDemo
#define _Included_NativeDemo
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: NativeDemo
* Method: test
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_NativeDemo_test (JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
4. 编写NativeDemo.c,实现Java_NativeDemo_test ();注意:不是test ()。代码如下:
// Java_NativeDemo_test()
#include
#include"NativeDemo.h"
#include
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(obj);
fid=(*env).GetFieldID(cls,"i","I");
if(fid==0){
printf("Could not get field ID./n");
return;
}
i=(*env).GetIntField(obj,fid);
printf("i=%d/n",i);
(*env).SetIntField(obj,fid,2*i);
printf("Ending the Native method./n");
}
5. 创建NativeDemo.dll
(1)如图,打开VS2008创建一个Win32工程
单击【OK】【Next】,设置应用程序类型为DLL
工程创建完毕。注意右上角的 ,在此将工程设置为Win32、Release
(2)设置工程属性。主要是将jni.h所在目录添加到工程的Include路径中
如图,点击【Additional Include Directories】后的浏览按钮
在弹出的窗口中双击空白行,点击浏览按钮
在弹出的窗口中浏览%JAVA_HONE%/include
同理,将%JAVA_HONE%/include/win32也添加进来
(3)将NativeDemo.h添加到工程
将NativeDemo.h拷贝到工程源文件目录:
D:/My Documents/Visual Studio 2008/Projects/NativeDemo/NativeDemo
下。如图,右键单击【Head Files】选择【Add】【Exiting Item...】
然后选中NativeDemo.h
(4)编写NativeDemo.cpp
将NativeDemo.c中的全部代码COPY到NativeDemo.cpp中的行
#include "stdafx.h"
下面,保存文件
(5)为NativeDemo.dll添加版本信息
如图,添加【Resource...】
选择【Version】,然后进行相关设置
(6)编译生成NativeDemo.dll
工程最后包含的文件如图:
选择【Build】【Build Solution】,经过调试,最后生成NativeDemo.dll
创建NativeDemo.dll完成。
6. 运行程序
将NativeDemo.dll拷贝到与NativeDemo.class相同的目录下,在CMD里输入
java NativeDemo
OK,使用JNI成功了! ^_^