http://blog.sina.com.cn/s/blog_4dbbf76f01000anz.html
1 delphi编写DLL 2 下面在delphi中编写一个简单的dll,在该dll中只有一个max函数,返回2个数中的大数(Delphi 5.0) 3 1、New->DLL;取名为DLL_0001,编写代码: 4 library dll_0001; 5 uses 6 SysUtils, 7 Classes; 8 {$R *.RES} 9 function max(x,y:integer):integer;stdcall; 10 begin 11 if(x>y) then 12 max :=x 13 else 14 max :=y; 15 end; 16 exports max; 17 begin 18 end. 19 红色部分为自己编写,这里和普通的delphi函数是一样的,只是在返回值中带个stdcall参数,然后用exports把函数导出 20 ================================================================================ 21 Delphl调用dll 22 调用dll分动态调用和静态调用2中,动态调用写起来简单,安全点,动态调用复杂很多,但很灵活; 23 现在编写一个程序,来调用上面写的dll_0001.dll文件中的max函数 24 一、new一个Application,在Form中放入2个TEdit、1个TLabek; 25 二、 26 1、静态调用 27 unit Unit1; 28 interface 29 uses 30 Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, 31 StdCtrls; 32 type 33 TForm1 = class(TForm) 34 Edit1: TEdit; 35 Edit2: TEdit; 36 Label1: TLabel; 37 procedure Edit2KeyDown(Sender: TObject; var Key: Word; 38 Shift: TShiftState); 39 private 40 { Private declarations } 41 public 42 { Public declarations } 43 end; 44 var 45 Form1: TForm1; 46 implementation 47 {$R *.DFM} 48 function max(x,y:integer):integer;stdcall; 49 external 'dll_0001.dll'; 50 procedure TForm1.Edit2KeyDown(Sender: TObject; var Key: Word; 51 Shift: TShiftState); 52 begin 53 if key =vk_return then 54 label1.Caption :=IntToStr(max(StrToInt(Edit1.text),StrToInt(edit2.text))); 55 end; 56 end. 57 红色代码自己添加,其中external "dll_name"中的dll_name可以是dll的绝对路径,要是该dll文件在你的搜索路径中,可以直接写文件名,但是.dll不能少写 58 2、动态调用,代码如下; 59 unit Unit1; 60 interface 61 uses 62 Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, 63 StdCtrls; 64 type 65 TForm1 = class(TForm) 66 Edit1: TEdit; 67 Edit2: TEdit; 68 Label1: TLabel; 69 procedure Edit2KeyDown(Sender: TObject; var Key: Word; 70 Shift: TShiftState); 71 private 72 { Private declarations } 73 public 74 { Public declarations } 75 end; 76 var 77 Form1: TForm1; 78 implementation 79 {$R *.DFM} 80 procedure TForm1.Edit2KeyDown(Sender: TObject; var Key: Word; 81 Shift: TShiftState); 82 type 83 TFunc =function(x,y:integer):integer;stdcall; 84 var 85 Th:Thandle; 86 Tf:TFunc; 87 Tp:TFarProc; 88 begin 89 if key =vk_return then 90 begin 91 Th :=LoadLibrary('dll_0001.dll'); {load dll} 92 if(Th >0) then 93 try 94 Tp :=GetProcAddress(Th,PChar('max')); 95 if(Tp <>nil) then 96 begin { begin 1} 97 Tf :=TFunc(Tp); 98 Label1.Caption :=IntToStr( 99 Tf(StrToInt(Edit1.text),StrToInt(Edit2.text))); 100 end { end 1} 101 else 102 ShowMessage('function max not found.'); 103 finally 104 FreeLibrary(Th); 105 end 106 else 107 ShowMessage('dll_0001.dll not exsit.'); 108 109 end; 110 end; 111 end.