Delphi封裝類到DLL

因爲個人需要研究了一下封裝類到DLL。把他發表出來

用Delphi封裝類到DLL。

 

一個公共單元

複製代碼
 1 unit ITest;
 2 
 3 interface
 4 
 5 type
 6   IT = interface
 7     function GetString:string;
 8     procedure ShowMsg(p:PChar);
 9     procedure Msg;
10   end;
11 
12 implementation
13 
14 end.
複製代碼


類單元,這個寫在DLL裏面的

複製代碼
 1 unit UTest;
 2 
 3 interface
 4 
 5 uses
 6   SysUtils,
 7   Windows,
 8   ITest;
 9 
10 type
11   TTest = class(TInterfacedObject,IT)
12   private
13     i:Integer;
14   protected
15 
16   public
17     constructor Create; //override;
18     destructor Destroy; override;
19     function GetString:string;
20     procedure ShowMsg(p:PChar);
21     procedure Msg;
22   published
23 
24   end;    
25 
26 implementation
27 
28 constructor TTest.Create;
29 begin
30   i:=0;
31 end;
32 
33 destructor TTest.Destroy;
34 begin
35   inherited;
36 end;
37 
38 function TTest.GetString:string;
39 begin
40   Result := 'Test string';
41 end;
42 
43 procedure TTest.ShowMsg(p:PChar);
44 begin
45   MessageBox(0,p,'Test',MB_OK);
46 end;
47 
48 procedure TTest.Msg;
49 begin
50   Inc(i);
51   MessageBox(0,'Test MessageBox',PChar(IntToStr(i)),MB_OK);
52 end;
53 
54 end.
複製代碼

DLL的prj

複製代碼
 1 library Test;
 2 
 3 uses
 4   SysUtils,
 5   Classes,
 6   ITest in 'ITest.pas',
 7   UTest in 'UTest.pas';
 8 
 9 {$R *.res}
10 
11 function TestCreate:IT; stdcall;
12 begin
13   Result := TTest.Create;
14 end;  
15 
16 exports
17   TestCreate; //用此初始化
18 
19 begin
20 end.
複製代碼

 

DLL部分就這樣了,到EXE部分調用

複製代碼
 1 uses
 2   ITest;  //引用單元
 3 
 4 function TestCreate:IT; stdcall; external 'Test.dll' name 'TestCreate'; //引用DLL函數
 5 
 6 //聲明作爲測試
 7   private
 8     AA:IT;
 9     BB:IT;
10 
11 procedure TForm1.FormCreate(Sender: TObject);
12 begin
13   AA:= TestCreate;
14   BB:= TestCreate;
15 end;
16 
17 procedure TForm1.Button1Click(Sender: TObject);
18 begin
19   Button1.Caption := AA.GetString;
20 end;
21 
22 procedure TForm1.Button2Click(Sender: TObject);
23 begin
24   AA.ShowMsg('123abc');
25 end;
26 
27 procedure TForm1.Button3Click(Sender: TObject);
28 begin
29   AA.Msg;
30 end;
31 
32 procedure TForm1.Button4Click(Sender: TObject);
33 begin
34   BB.Msg;
35 end;
複製代碼


上效果圖效果圖

轉自:http://www.cnblogs.com/ruguo

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章