使用DELPHI编写动态链接库的例程
本例程是简单的动态链接库。且看下面的源码。经过编译后,产生了MinMax.DLL文件。函数或过程后面不能少了stdcall该关键字。
与主程序文件不同,在库单元中,将Program 关键被 library代替。
注意,函数或过程应在库单元的exports中写代说明代码。
library MinMax;
uses
SysUtils,
Classes,
fmMmUnit in 'fmMmUnit.pas';
{$R *.res}
exports
Min ,
Max ;
begin
;
end.
unit fmMmUnit;
interface
function Min(X, Y : integer):integer; stdcall;
function Max(X, Y : integer):integer; stdcall;
implementation
function Min(X, Y : integer):integer; stdcall;
begin
if X<Y then Result := X else Result := Y;
end;
function Max(X, Y : integer):integer; stdcall;
begin
if X>Y then Result := X else Result := Y;
end;
end.
若要你的库对其它语言编写的程序是可见的,最安全的办法是在声明输出函数时指定stdcall 调用约定,其它语言或许不支持Object Pascal 默认的register 调用约定。
调用动态链接库的例程见下例,关键代码请看蓝色加粗部分。
unit fmmaxmin;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TMaxMin = function (X, Y :integer):integer; stdcall;
TForm1 = class(TForm)
Edit1: TEdit;
Button1: TButton;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Edit2: TEdit;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
x,y: integer;
public
{ Public declarations }
end;
var
Form1: TForm1;
Max: TMaxMin;
Min: TMaxMin;
LibHand1 : THandle;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
x := 100;
y := 120;
Label1.Caption := '从 ' + IntToStr(x)+ Format('%2s和%2s',[' ',' ']) + IntToStr(y)
+ ' ' + '求最大数和最小数';
Edit1.Clear;
Edit2.Clear;
Caption := '动态连接库调用例程';
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
LibHand1 := LoadLibrary('MinMax.Dll');
try
if LibHand1 = 0 then
begin
Raise Exception.Create('load error');
end;
@Max := GetProcAddress(LibHand1, 'Max');
@Min := GetProcAddress(LibHand1, 'Min');
if not(@Max=nil) then
Edit1.Text := IntToStr(Max(x,y));
Edit2.Text := IntToStr(Min(x,y));
finally
FreeLibrary(LibHand1);
end;
end;
end.