來自http://www.pcbookcn.com/article/2325.htm總結(jié)
單一的一種程序語言的使用已經(jīng)不能滿足我們真正開發(fā)過程中遇到的問題,有可能會(huì)使用多種程序語言共同完成某一應(yīng)用,現(xiàn)在我講解一下java與C++共同完成對(duì)window2000的動(dòng)態(tài)連接庫(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
使他生成一個(gè)edu_netcom_jni_WinMsgBox.h頭文件,這個(gè)頭文件的文件名是包名加上類名共同組成的.頭文件內(nèi)容如下
/* 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
然后寫一個(gè)cpp文件實(shí)現(xiàn)這個(gè)頭文件,在這個(gè)方法里面調(diào)用了MessageBox()函數(shù)如下
#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里面生成一個(gè)dll文件,有的時(shí)候會(huì)報(bào)一個(gè)錯(cuò),意思是dll文件打不開,可以寫一個(gè)def文件,然后把所需要的lib文件定義在這個(gè)文件里面,內(nèi)容如下:
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目錄下 這樣通過調(diào)用native方法就執(zhí)行dll里面定義的相應(yīng)的操作了 very easy!
聯(lián)系客服