1创建Dll
下面是建立动态链接库的具体步骤:
(1)启动Delphi。
(2)在IDE选择File|New命令,在New Items对话框选择DLL,
Delphi将为你创建一个DLL程序的外壳。
(3)添加要实现的过程或函数。
示例:
library lx1;
uses
SysUtils,
Classes;
function lx(i,j:Integer):Integer;stdcall;
begin
Result:=i+j;
end;
exports lx;
end.
2静态调用。
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
function lx(i,j:Integer):Integer;stdcall;
External 'lx1.dll' Name 'lx';
//上面一行是静态调用时声明方法。
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
begin
Button1.Caption:=inttostr(lx(1,2));
end;
end.
3动态调用
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
type
TMyfunc=function (i,j:Integer):Integer;stdcall;
procedure TForm1.Button1Click(Sender: TObject);
var
Myfunc : TMyFunc;
MyHandle: THandle;
begin
MyHandle:=LoadLibRaRy('lx1.dll');
if MyHandle<=0 then
begin
Raise Exception.Create('动态连接库lx1.dll加载失败,其原因(错误代码)是:'+IntToStr(GetLastError));
end else
begin
@MyFunc:=GetProcAddress(MyHandle,'lx');
if not Assigned(MyFunc) then
begin
Raise Exception.Create('动态连接库lx1.dll的lx函数调用失败,其原因(错误代码)是:'+IntToStr(GetLastError));
end else
begin
Button1.Caption:=inttostr(MyFunc(1,2));
end;
end;
FreeLibrary(MyHandle);
end;
end.