如何在Java中调用dll

| No Comments | No TrackBacks

我知道的有两种方法,一种是直接用JNI,另一种是则是用Jacob(实质上也用的是JNI)

先讲讲第一种方法

1.编写java程序TestDll,注意,这个类有两个作用,一个是用来做头文件,另外一个作用就是通过它来调用dll
public class TestDll {
static
{
System.loadLibrary("DLLSample");//载入dll
}
public native static int DoubleValue(int i);//函数声明
}

2.编译: javac TestDll
3.生成头文件: javah TestDll
生成TestDll.h文件,这里面只对函数DoubleValue作了声明
/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class TestDll */

#ifndef _Included_TestDll
#define _Included_TestDll
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: TestDll
* Method: DoubleValue
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_TestDll_DoubleValue
(JNIEnv *, jclass, jint);

#ifdef __cplusplus
}
#endif
#endif


4.用vc制作DLL
修改DLLSample工程,程序中添加函数DoubleValue的实现,函数名必须用jni规定格式,可以照到.h文件里的声

明来写:

#include "jni_md.h"
#include "TestDll.h"

JNIEXPORT jint JNICALL Java_TestDll_DoubleValue (JNIEnv *, jclass, jint p)
{
int j = p*2;
return j;

JNIEXPORT,JNICALL,JNIEnv *, jclass请都不要动,jint对应是java里的int

别忘了把TestDll.h,jni.h(这个文件在jdk/include下),jni_md.h(这个文件在jdk/include/win32下)复制到VC

工程目录中,然后编译生成dll

5.把生成的DLLSample.dll复制到jdk/bin下(确保PATH指向了这个目录)

6.应用
我看到他们举的例子都是把调用写在了main里, 在这里我把应用取出来放在一个servlet类中的测试的,同样可

以得到正确结果,这里体现国TestDll的第二个作用,它是调用dll的一个纽带
......
TestDll td = new TestDll();
System.out.println("result= "+td.DoubleValue(25));
.....


注意:
如果更改了TestDll的内容或重使命名了这个文件,必须重新用它生成头文件,在dll里也要做相应修改,

因为必须要和java里面的声明一致才行

No TrackBacks

TrackBack URL: http://www.wujianrong.com/mt-tb.cgi/427

Leave a comment

About this Entry

This page contains a single entry by kevinwu published on February 14, 2006 10:29 AM.

JNI调用固有方法 was the previous entry in this blog.

JBuilder9制作EXE文件 is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.