因为个人需要研究了一下封装类到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;
上效果图