Delphi dll定义与调用

来源:互联网 发布:玩骰子的软件 编辑:程序博客网 时间:2024/06/01 10:00

1.dll定义

library testdll;uses  SysUtils,  Classes;Function add (X,Y:integer ):integer;stdcall ;begin  Result := X+Y;end ;{$R *.res}exports  add ;beginend.

2.静态调用dll

       优点:可以通过depends查看dll依赖项,同时在程序执行前就可以知道程序的是否完整

       缺点:如果dll不使用也会被加载进来,造成内存浪费,某个dll损坏,也会造成整程序不能运行

unit usedll;interfaceuses  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,  Dialogs, StdCtrls;type  TForm1 = class(TForm)    btn1: TButton;    procedure btn1Click(Sender: TObject);  private    { Private declarations }  public    { Public declarations }  end;var  Form1: TForm1;Function add (X ,Y :integer ):integer;stdcall ;external 'E:\test5\testdll.dll' ;implementation{$R *.dfm}procedure TForm1.btn1Click(Sender: TObject);begin  ShowMessage (IntToStr(add(30,50))) ;end;end.


3.动态调用dll

          缺点:不能查看dll依赖项,程序执行前不能知道程序是否完整,某个dll损坏不可以预知

         优点:dll按需加载到内存,节省内存,部分dll损坏不影响程序的其他部分正常运行

unit usedll;interfaceuses  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,  Dialogs, StdCtrls;type  TForm1 = class(TForm)    btn1: TButton;    procedure btn1Click(Sender: TObject);  private    { Private declarations }  public    { Public declarations }  end;var  Form1: TForm1;implementation{$R *.dfm}procedure TForm1.btn1Click(Sender: TObject);var  handle:THandle;  sdll:string;  add:function(x,y:integer):integer;StdCall;begin  sdll:='E:\dll\testdll.dll';  handle:=LoadLibrary(PAnsiChar(sdll));  if handle<>0 then  begin    @add:=GetProcAddress(handle, 'add');    if @add<>nil then    ShowMessage(IntToStr(add(2,2)));    FreeLibrary(handle);  end;end;end.
                                             
0 0
原创粉丝点击