Delphi 动态链接库

不是原创,只是看到好的内容复制了保存下来,留着学习。

动态链接库(原文链接)

一、DLL

New——Others——Delphi Projects——DLL Wizard

uses
SysUtils,
Classes;
function incc(a,b:integer):Integer; stdcall; //真正的代码开始;
begin
Result :=a+b;
end;
{$R *.res}


exports //允许调用;
incc;


end.

二、调用

1.静态调用

var
Form1: TForm1;

implementation

function incc(a,b:Integer):Integer;stdcall; external 'Project1.dll'; //加载这个动态库。

{$R *.dfm}

procedure TForm1.btn1Click(Sender: TObject);
var
aa:Integer;
begin
aa:=incc(StrToInt(edt1.Text),StrToInt(edt2.Text));//开始调用
ShowMessage(IntToStr(aa));//弹出结果。
end;

end.

2.动态调用

动态载入方式是指在编译之前并不知道将会调用哪些 DLL 函数, 完全是在运行过程中根据需要决定应调用哪些函数。

LoadLibrary : 将指定的模块加载到调用进程的地址空间中,返回值是模块的句柄。
GetProcAddress:检索指定的动态链接库(DLL)中的输出库函数地址
var
Form1: TForm1;

implementation

{$R *.dfm}

type
Tmyfun = function (a,b:integer):Integer; stdcall;//定义一个函数类型,注意一点过程类型种的参数应该与DLL中用到的方法的参数一致。

procedure TForm1.btn1Click(Sender: TObject);
var
myhandle:THandle;
FPointer:Pointer;
Myfun :Tmyfun;
begin
  myhandle:=LoadLibrary('C:\Documents and Settings\Administrator\桌面\新建文件夹\Project1.dll') ;//加载这个DLL
  if myhandle >0 then//加载成功就执行。
  try
    FPointer :=GetProcAddress(myhandle,PChar('incc')); //取函数的地址。
    if FPointer <>nil then //如果函数存在就调用
    begin
      Myfun := Tmyfun(FPointer);
      showmessage(IntToStr(Myfun(StrToInt(edt1.Text),StrToInt(edt2.Text))));//弹出算出的结果。
    end;
  except
    FreeLibrary(myhandle);
  end;
end;

end.

 

 

posted @ 2019-11-07 14:11  小党丶先生  阅读(611)  评论(0编辑  收藏  举报