資源描述:
《delphi之調用外部dll中的函數(shù)》由會員上傳分享,免費在線閱讀,更多相關內容在行業(yè)資料-天天文庫。
1、分早綁定和晚綁定兩種。早綁定的代碼如下:unitUnit1;interfaceuses??Windows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,??Dialogs,StdCtrls;type??TForm1=class(TForm)????Button1:TButton;????procedureButton1Click(Sender:TObject);??private????{Privatedeclarations}??public????{Publicdeclarations}??
2、end;var??Form1:TForm1;//MB函數(shù)的聲明:functionMB(hWnd:HWND;lpText,lpCaption:PChar;uType:UINT):Integer;stdcall;implementation{$R*.dfm}{調用外部DLL中的函數(shù),譬如調用系統(tǒng)user32.dll中的MessageBoxA}//functionMB(hWnd:HWND;lpText,lpCaption:PChar;uType:UINT):Integer;//??stdcall;externaluser32name'MessageBoxA';{其中use
3、r32是Delphi定義的常量'user32.dll',可以直接寫成:}//functionMB(hWnd:HWND;lpText,lpCaption:PChar;uType:UINT):Integer;//??stdcall;external'user32.dll'name'MessageBoxA';{name后面說明函數(shù)的真實名字}{external子句說明單元載入時就加載函數(shù),也就是早綁定;如果晚綁定需要用LoadLibrary}{stdcall指令表示參數(shù)傳遞是從右到左(Pascal則反之),不通過CPU寄存器傳遞}{4個參數(shù)的數(shù)據(jù)類型可以使用對應的Delp
4、hi數(shù)據(jù)類型,譬如:}//functionMB(hWnd:LongWord;lpText,lpCaption:PChar;uType:LongWord):Integer;//??stdcall;external'user32.dll'name'MessageBoxA';{或者是:}//functionMB(hWnd:Cardinal;lpText,lpCaption:PChar;uType:Cardinal):Integer;//??stdcall;external'user32.dll'name'MessageBoxA';{如果函數(shù)在此單元聲明后,需要給其他單元調
5、用,需要先在interface區(qū)聲明:}//functionMB(hWnd:Cardinal;lpText,lpCaption:PChar;uType:Cardinal):Integer;//??stdcall;{本例已經這樣做了,如果要測試其他幾種情況,需要先注釋掉它}{然后在implementation區(qū),說明函數(shù)的來源:}functionMB;external'user32.dll'name'MessageBoxA';//調用測試:procedureTForm1.Button1Click(Sender:TObject);var??t,b:??PChar;beg
6、in??t:='標題';??b:='內容';??MB(0,b,t,0);end;end.晚綁定的例子:unitUnit1;interfaceuses??Windows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,??Dialogs,StdCtrls;type??//晚綁定,也就是動態(tài)調用外部函數(shù)主要用以下三個命令:??//LoadLibrary:獲取DLL??//GetProcAddress:獲取函數(shù)??//FreeLibrary:釋放??//定義一個過程類型,參數(shù)要和需要的函數(shù)一致??TMB
7、=function(hWnd:HWND;lpText,lpCaption:PChar;uType:UINT):Integer;stdcall;??TForm1=class(TForm)????Button1:TButton;????procedureButton1Click(Sender:TObject);????procedureFormCreate(Sender:TObject);????procedureFormDestroy(Sender:TObject);??private????MB:TMB;??{聲明函數(shù)MB}????inst:LongWord;?