DLL的编写和使用
開使你的第一個DLL專案 1.File->Close all->File->New﹝DLL﹞
?代碼:
//自動產生Code如下:
?ibrary Project2;
//這有段廢話。
??uses ? ?
SysUtils,?? Classes;
{$R *.RES}
begin
end.
2.加個Func進來:
代碼:
?library Project2;
uses ?
?SysUtils, ? Classes;???????
Function MyMax ( X , Y : integer ) : integer ; stdcall ; ? ? ? ?
?begin ? ?
??? if X > Y then ? ?
??????? Result := X ? ?
??? else ? ?
??????? Result := Y ; ?
????? end ; ?
? //切記:Library 的名字大小寫沒關系,可是DLL-Func的大小寫就有關系了。????
//? ? 在 DLL-Func-Name寫成MyMax與myMAX是不同的。如果寫錯了,立即的結果是你調用到此DLL的AP根本開不起來。 ? ?
?//參數的大小寫就沒關系了。甚至不必同名。如原型中是 (X,Y:integer)但引用時寫成(A,B:integer),那是沒關系的。 ? ?
//切記:要再加個stdcall。書上講,如果你是用Delphi寫DLL,且希望不僅給?Delphi-AP也希望BCB/VC-AP等使用的話,那你最好加個Stdcall ;?
?//參數型態:Delphi有很多種它自己的變量型態,這些當然不是DLL所喜歡的,Windows/DLL的母語應該是C。所以如果要傳進傳出DLL的參數,我們盡可能照規矩來用。這兩者寫起來,后者會麻煩不少。如果你對C不熟的話,那也沒關系。我們以后再講。
{$R *.RES} begin end.
3.將這些可共享的Func送出DLL,讓外界﹝就是你的Delphi-AP啦﹞使用:
光如此,你的AP還不能用到這些,你還要加個Exports才行。 代碼:
{$R *.RES}
exports
??? MyMax ;
begin
end.
4.好了,可以按 Ctrl-F9編譯了。此時可不要按F9。DLL不是EXE不可單獨執行的,如果你按F9,會有ErrorMsg的。這時如果DLL有Error,請修正之。再按Ctrl-F9。此時可能有Warning,不要緊,研究一下,看看就好。再按Ctrl-F9,此時就『Done , Compiled 』。同目錄就會有個 *.dll 。恭喜,大功告成了。
library Project2;{ Important note about DLL memory management: ShareMem must be thefirst unit in your library's USES clause AND your project's (selectProject-View Source) USES clause if your DLL exports any procedures orfunctions that pass strings as parameters or function results. Thisapplies to all strings passed to and from your DLL--even those thatare nested in records and classes. ShareMem is the interface unit tothe BORLNDMM.DLL shared memory manager, which must be deployed alongwith your DLL. To avoid using BORLNDMM.DLL, pass string informationusing PChar or ShortString parameters. }usesSysUtils,Classes;{$R *.res}Function MyMax ( X , Y : integer ) : integer ; stdcall ; beginif X > Y then Result := Xelse Result := Y end;exportsMyMax ;begin end.
?二、進行測試:開個新application:
?1.加個TButton 代碼:
?ShowMessage ( IntToStr(MyMax(30,50)) ) ;
2.告知Exe到那里抓個Func 代碼:
?//在Form,interface,var后加
Function MyMax ( X , Y : integer ) : integer ; stdcall ;
?external 'MyTestDLL.dll' ;
?// MyTestDLL.dll為你前時寫的DLL項目名字,DLL名字大小寫沒關系。不過記得要加extension的.DLL。在Win95或NT,?是不必加 extension,但這兩種OS,可能越來越少了吧。
unit Unit1;interfaceusesWindows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,Dialogs, StdCtrls;typeTForm1 = class(TForm)Button1: TButton;procedure Button1Click(Sender: TObject);private{ Private declarations }public{ Public declarations }end;varForm1: TForm1;Function MyMax ( X , Y : integer ) : integer ; stdcall ; external 'Project2.dll' ;implementation{$R *.dfm}procedure TForm1.Button1Click(Sender: TObject); beginShowMessage ( IntToStr(MyMax(30,50)) ) ; end;end.
?
超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
- 上一篇: delphi7下安装TMS compon
- 下一篇: delphi调用windows api