Delphi DLL 的编写
Delphi DLL 的编写 By Shaoyun 2010-03-18
最近打算继续学习Delphi,平常很少用,现在又有很长时间没动了!顺便将学习的内容写下来备忘!
例子代码:
代码
1 library SYLib;
2 uses
3 SysUtils,Classes;
4 {$R *.res}
5 function Max(x:Integer; y: Integer):Integer;stdcall;
6 begin
7 if x>y then
8 Result:= x
9 else
10 Result:= y;
11 end;
12
13 exports
14 Max;
15
16 begin
17 end.
2 uses
3 SysUtils,Classes;
4 {$R *.res}
5 function Max(x:Integer; y: Integer):Integer;stdcall;
6 begin
7 if x>y then
8 Result:= x
9 else
10 Result:= y;
11 end;
12
13 exports
14 Max;
15
16 begin
17 end.
Dephi为fastcall调用方式,C/C++是stdcall调用,为了DLL能让这些程序调用,最好声明为stdcall类型,exports导出函数,不导出是没法调用的!
调用方法有静态和动态两种:
静态调用,也是最常用的一种方法
在var后声明
function Max(x:Integer;y:Integer):Integer;stdcall; external 'SYLib.dll'
调用和平常一样,如下:
procedure TForm1.btn1Click(Sender: TObject);
begin
ShowMessage(IntToStr(Max(2,3)));
end;
begin
ShowMessage(IntToStr(Max(2,3)));
end;
动态调用,麻烦些:
1 procedure TForm2.btn1Click(Sender: TObject);
2 type
3 TFunType=function(x:Integer;y:Integer):Integer;stdcall;
4 var
5 dllHandle:THandle;
6 pfun:TFarProc;
7 _Max:TFunType;
8 begin
9 dllHandle:= LoadLibrary('SYLib.dll');
10 if dllHandle>0 then
11 try
12 pfun:=GetProcAddress(dllHandle,PAnsiChar('Max'));
13 if pfun<>nil then
14 begin
15 _Max:=TFunType(pfun);
16 ShowMessage(IntToStr(_Max(2,3)));
17 end
18 else
19 ShowMessage('没有找到Max函数!');
20 finally
21 FreeLibrary(dllHandle);
22 end
23 else
24 ShowMessage('没有找到SYLib.dll!');
25 end;
2 type
3 TFunType=function(x:Integer;y:Integer):Integer;stdcall;
4 var
5 dllHandle:THandle;
6 pfun:TFarProc;
7 _Max:TFunType;
8 begin
9 dllHandle:= LoadLibrary('SYLib.dll');
10 if dllHandle>0 then
11 try
12 pfun:=GetProcAddress(dllHandle,PAnsiChar('Max'));
13 if pfun<>nil then
14 begin
15 _Max:=TFunType(pfun);
16 ShowMessage(IntToStr(_Max(2,3)));
17 end
18 else
19 ShowMessage('没有找到Max函数!');
20 finally
21 FreeLibrary(dllHandle);
22 end
23 else
24 ShowMessage('没有找到SYLib.dll!');
25 end;
暂时就这些! Delphi2010 / Windows SP3 下测试!