Delphi编写DLL

library MyDLL;

uses
  SysUtils,
  Classes;
{$R *.res}

{加上stdcall表示此DLL文件可以供除Delphi以外程序调用,比如VB、C++等等}
function MySquare(num:integer):integer; stdcall;
begin
  Result:=num*num;
end;

exports
  MySquare; {输出MySquare()函数,必须输出,否则在程序中调用时会提示"无法找到此函数的入口点"}
begin
end.

静态加载方式调用DLL

 

unit Unit1;
interface
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;
type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
  {静态调用}
  function MySquare(i:integer):integer; stdcall; external 'MyDLL.dll';
  {静态调用使用别名方式}
  function MyAsSqr(i:integer):integer; stdcall; external 'MyDLL.dll' name 'MySquare';
var
  Form1: TForm1;
  {静态调用时也可以定义在这里
  function MySquare(i:integer):integer; stdcall; external 'MyDLL.dll'; }

implementation
{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage(IntToStr(MySquare(5)));
  ShowMessage(IntToStr(MyAsSqr(6)));
end;
end.

 

动态加载方式调用DLL

 

unit Unit1;

interface
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;
type
  TForm1 = class(TForm)
    Button1: TButton;
    //Memo1: TMemo;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
  {动态调用}
  TMySquare = function(i:integer):integer; stdcall;
var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  num: integer;
  HndDLL: THandle;
  {为便于演示代码,此处使用Func来命名}
  Func: TMySquare;
  {实际开发中我更习惯使用此方式命名
  MySquare: TMySquare; }
begin
  HndDLL := LoadLibrary('MyDLL.dll');
  try
    //注意'MySquare'为DLL中的原始名称
    @Func := GetProcAddress(HndDLL, 'MySquare');
    //@MySquare:= GetProcAddress(HndDLL, 'MySquare');
    if Assigned(@Func) then
    //if not (@Func=nil) then
    begin
      num := Func(7);
      ShowMessage(IntToStr(num)) ;
      //self.Memo1.Lines.Add(IntToStr(num));
    end;
  finally
    FreeLibrary(HndDLL);
  end;
end;
end.

 

静态加载:简单方便。

动态加载:相对复杂一些,需要显示得获取函数调用地址,但比较灵活,对于不常用的代码,使用时LoadLibrary,不用时FreeLibrary,不必长时间占用内存资源。

 

 

posted on 2014-06-05 09:55  二进制的猫  阅读(201)  评论(0)    收藏  举报