1. 共享代码、资源和数据
2. 隐藏实现的细节
3. 拓展开发工具如Delphi的功能
1. Load-time Dynamic Linking
2. Run-time Dynamic Linking
1. 静态调用方式
该DLL的程序代码如下:
library AddNum;
uses
SysUtils,
Classes;
{$R *.res}
function AddNumber(Num1,Num2:integer):integer;stdcall; //定义求和函数
begin
result:=Num1+Num2;
end;
exports
AddNumber; //引出求和函数
begin
end.
function AddNum(Num1,Num2:integer):integer;stdcall;external 'AddNum.dll'
name 'AddNumber';
procedure TForm1.Button1Click(Sender: TObject);
var
Number1,Number2:integer;
Sum:integer;
begin
Number1:=strtoint(Edit1.Text);
Number2:=strtoint(Edit2.Text);
Sum:=AddNum(Number1,Number2); //调用求和函数计算结果
Edit3.Text:=inttostr(Sum);
end;
2.动态调用方式
function ShowCalendar(AHandle: THandle; ACaption: String): TDateTime;
var
DLLForm: TDLLForm;
begin
Application.Handle := AHandle;
DLLForm := TDLLForm.Create(Application); //创建并显示窗体
try
DLLForm.Caption := ACaption;
DLLForm.ShowModal; //显示方式为模式化
Result := DLLForm.calDLLCalendar.CalendarDate; //返回设定日期
finally
DLLForm.Free; //用完后卸载该窗体
end;
end;
procedure TMainForm.Button1Click(Sender: TObject);
var
OneHandle : THandle; //定义一个句柄变量
begin
OneHandle := LoadLibrary('Clendar.dll'); //动态载入DLL,并返回其句柄
try
if OneHandle <> 0 then //如果载入成功则获取ShowCalendar函数的地址
@ShowCalendar := GetProcAddress(OneHandle, 'ShowCalendar');
if not (@ShowCalendar = nil) then
//如果找到该函数则在主窗体的Label1中显示DLL窗体中设定的日期
Label1.Caption := DateToStr(ShowCalendar(Application.Handle, Caption))
else
RaiseLastWin32Error;
finally
FreeLibrary(OneHandle); //调用完毕收回DLL占用的资源
end;
end;