关于java调用window DLL里的函数的总结

来源:百度文库 编辑:神马文学网 时间:2024/04/26 11:46:21
来自http://www.pcbookcn.com/article/2325.htm总结
单一的一种程序语言的使用已经不能满足我们真正开发过程中遇到的问题,有可能会使用多种程序语言共同完成某一应用,现在我讲解一下java与C++共同完成对window2000的动态连接库(DLL)的使用
首先定义一下java类WinMsgBox如下
public class WinMsgBox {
static{
System.loadLibrary("WinMsgDll");
}
public native void showMsgBox(String str);
public static void main(String[] args){
WinMsgBox ss = new WinMsgBox();
ss.showMsgBox("Hello World!");
}
}
然后使用javah命令生成头文件 如下:
C:\tmp>javah -classpath . -jni edu.netcom.jni.WinMsgBox
使他生成一个edu_netcom_jni_WinMsgBox.h头文件,这个头文件的文件名是包名加上类名共同组成的.头文件内容如下
/* DO NOT EDIT THIS FILE - it is machine generated */ #include /* Header for class edu_netcom_jni_WinMsgBox */
#ifndef _Included_edu_netcom_jni_WinMsgBox
#define _Included_edu_netcom_jni_WinMsgBox
#ifdef __cplusplus extern "C" {
#endif
/* * Class: edu_netcom_jni_WinMsgBox
* Method: showMsgBox
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_edu_netcom_jni_WinMsgBox_showMsgBox (JNIEnv *, jobject, jstring);
#ifdef __cplusplus
}
#endif
#endif
然后写一个cpp文件实现这个头文件,在这个方法里面调用了MessageBox()函数如下
#include "windows.h"
#include "iostream.h"
//#include "source.h"
#include "edu_netcom_jni_WinMsgBox.h"
/* * Class: edu_netcom_jni_WinMsgBox
* Method: showMsgBox
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_edu_netcom_jni_WinMsgBox_showMsgBox (JNIEnv * env, jobject obj, jstring str){
const char *msg; msg = env->GetStringUTFChars(str,0);
MessageBox(NULL,msg,"Java invoke",MB_OK);
env->ReleaseStringUTFChars(str,msg);
}
然后在vc里面生成一个dll文件,有的时候会报一个错,意思是dll文件打不开,可以写一个def文件,然后把所需要的lib文件定义在这个文件里面,内容如下:
LIBRARY      "WinMsgDll"
DESCRIPTION  ‘message Windows Dynamic Link Library‘
EXPORTS
; Explicit exports can go here
Java_edu_netcom_jni_WinMsgBox_showMsgBox
文件名为WinMsgDll.dll,再把WinMsgDll.dll文件放到c:\winnt\system32目录下 这样通过调用native方法就执行dll里面定义的相应的操作了 very easy!