使用DELPHI编写动态链接库的例程

使用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.

 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值