DLL的调用方法

来源:互联网 发布:淘宝吉他店哪个好 编辑:程序博客网 时间:2024/06/03 00:25

1.定义DLL中需要调用的函数  TShowFrm = procedure(App: TApplication  参数一; Scr: TScreen  参数二 ); stdcall;(无需定义函数或过程名,只需要定义是否为过程或者函数,参数的数量及格式);
2.定义hInstance:THandle变量,采用hInstance := LoadLibrary('Projectdll.dll')获取DLL地址;
3.定义 AFunc: Pointer;指针变量,采用Pointer(AFunc) := GetProcAddress(hInstance, PChar('ShowFrm'));获取函数地址;
4.执行函数 TShowFrm(AFunc)(Application, Screen), 定义的函数名(函数地址)(函数需要的参数一,参数二);

 

----------------------------------------------------------------------------------
unit Unit1;
interface
uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.ToolWin, Vcl.StdCtrls;
type
  TShowFrm = procedure(App: TApplication; Scr: TScreen); stdcall;//定义需要在DLL调用的函数或过程
type
  TForm1 = class(TForm)
    ToolBar1: TToolBar;
    ToolButton1: TToolButton;
    Edit1: TEdit;
    Button2: TButton;
    Button3: TButton;
    Button4: TButton;
    Button1: TButton;
    Button5: TButton;
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Button4Click(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button5Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    hInstance: THandle;//定义用来获取DLL地址的指针变量
  end;

var
  Form1: TForm1;
implementation

{$R *.DFM}
procedure TForm1.Button2Click(Sender: TObject);
begin
  try
    hInstance := LoadLibrary('Projectdll.dll');//LOAD DLL 将地址赋给DLL指针变量
    { load the library on form create as will need to know what forms are available, so they can be listed for creation. }
  except
    on e: exception do
      ShowMessage(e.Message);
  end;
end;


procedure TForm1.Button3Click(Sender: TObject);
var
  AFunc: Pointer;//定义函数过程指针
begin
  try
    Pointer(AFunc) := GetProcAddress(hInstance, PChar('ShowFrm'));//将在DLL中获取函数的地址赋给函数指针
    TShowFrm(AFunc)(Application, Screen);//将TSHOWFRM类的地址指针赋值为DLL中的地址,然后执行,(赋予参数Application, Screen)。
    { Open the child form }
  except
    on e: exception do
      ShowMessage(e.Message);
  end;
end;

原创粉丝点击