1. 编写所需要调用到C DLL的java源文件,这里取名为TestJNI.java,放置在D:/根目录。
package myTest;
public class TestJNI{
private native int add(int x,int y);
public static void main(String[] args) {
TestJNI testJNI = new TestJNI();
int result = testJNI.add(1, 2);
System.out.println("result = " + result);
}
static {
System.loadLibrary("myDll");
}
}
2. 产生头文件TestJNI.h。首先编译TestJNI.java。cmd到D:/根目录运行:javac -d d:/ TestJNI.java,然后运行javah myTest.TestJNI,则会生成TestJNI.h。其中的内容为:
#include "jni.h"
#ifndef _Included_TestJNI
#define _Included_TestJNI
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT jint JNICALL Java_myTest_TestJNI_add (JNIEnv *, jobject, jint, jint);
#ifdef __cplusplus
}
#endif
#endif
注:最后要运行TestJNI的时候,在D:/根目录下运行 java myTest.TestJNI 就可以了。
3. 创建一个VC++空项目,用于生成一个myFirstDll.dll。而这个dll会在myDll.dll中被调用。往空项目中有新添加入两个文件First.h和First.c,内容为:
First.h
---------
#ifndef FIRST_H
#define FIRST_H
_declspec(dllexport) int myAdd(int, int);
#endif
First.c
---------
#include "First.h"
_declspec(dllexport) int myAdd(int i, int j)
{
return i + j;
}
随后编译项目,可得到myFirstDll.lib和myFirstDll.dll文件。
4. 新建一个VC++空项目,创建一个新文件myDll.c,将上面生成的myFirstDll.lib,myFirstDll.dll和First.h拷贝到这个新项目中,将第2步产生的TestJNI.h文件也拷贝到这个项目中。编辑myDll.c的内容为:
myDll.c
------------
#include "TestJNI.h"
#include "First.h"
JNIEXPORT jint JNICALL Java_myTest_TestJNI_add
(JNIEnv *ev, jobject obj, jint x, jint y)
{
return myAdd(x, y);
}
在VC项目的C/C++属性的Additional Include Directories中添加%JAVA_HOME%/include/;%JAVA_HOME%/include/win32。然后可以编译项目生成myDll.dll。
5. 将myFirstDll.dll,myDll.dll拷贝到D:/根目录。运行java myTest.TestJNI,就会输出1+2的结果3了。