但是静态方法不能灵活地在运行时装卸所需的DLL,而是在主程序开始运行时就装载指定的DLL直到程序结束时才释放该DLL,另外只有基于编译器和链接器的系统(如Delphi)才可以使用该方法。
1. 静态调用方式
主程序在调用该DLL 时,首先在interface 部分声明要调用的函数:
//导出过程
procedure Test; external 'ProjectDll.dll';
//导出函数
function add(a, b: Integer): Integer;stdcall; external 'ProjectDll.dll';
procedure TForm1.btn1Click(Sender: TObject);
begin
ShowMessage(add(10, 20).ToString);
end;
PS:在其他工程调用,如果不在一个工程组,需要在相同目录下、System32下或指定路径;声明可以在实现区或接口区,这里的函数名要一致,甚至大小写。
2. 动态调用方式
dll代码
function sub(a, b: Integer): Integer; stdcall;
begin
Result := a - b;
end;
exports
sub;
interface部分声明
type
//定义一个函数类型,参数要和需要的函数一致
sub1 = function(a, b: Integer): Integer; stdcall;
TForm1 = class(TForm)
btn1: TButton;
btn2: TButton;
procedure btn1Click(Sender: TObject);
procedure btn2Click(Sender: TObject);
private
{ Private declarations }
MB: sub1; {声明函数 MB}
inst: LongWord; {声明一个变量来记录要使用的 DLL 句柄}
public
{ Public declarations }
end;
调用实现
procedure TForm1.btn2Click(Sender: TObject);
begin
try
//动态载入DLL ,并返回其句柄
inst := LoadLibrary('ProjectDll.dll');
if inst <> 0 then
begin
MB := GetProcAddress(inst, 'sub');
ShowMessage(MB(30, 10).ToString);
end;
finally
//记得释放
FreeLibrary(inst);
end;
end;
来源:http://www.coder163.com/language/delphi/console/Dll%E5%88%9B%E5%BB%BA%E5%B9%B6%E8%B0%83%E7%94%A8.html