似乎只有一种方法 - 创建一个回调对象.在你的应用程序中,你必须声明接口,它描述了你的方法,例如:
IMyMethodInterface = interface(IInterface)
procedure MyMethod(); stdcall;
end;
Run Code Online (Sandbox Code Playgroud)
接下来你必须创建类,它实现了这个接口(和你的方法):
TMyMethodObject = class(TInterfacedObject, IMyMethodInterface)
public
procedure MyMethod(); stdcall;
end;
Run Code Online (Sandbox Code Playgroud)
加载DLL时,必须创建TMyMethodObject实例并将其传递IMyMethodInterface给dll; 当然dll必须有相应的方法并导出它(以接口为参数)SetMethodCallback存储接口参考:
瓦尔:
var mmo : IMyMethodInterface;
dllHandle : THandle;
smc : procedure (mmi : IMyMethodInterface); stdcall;
Run Code Online (Sandbox Code Playgroud)
码:
mmo := TMyMethodObject.Create();
dllHandle := LoadLibrary('mydll.dll');
smc := GetProcAddress(dllHandle, 'SetMethodCallback');
if assigned(smc) then
smc(mmo);
Run Code Online (Sandbox Code Playgroud)
现在,您可以在dll中使用IMyMethodInterface引用来调用方法.
当然你可以静态链接DLL并直接使用它:
procedure SetMethodInteface(mmi : IMyMethodInterface); stdcall; external 'mydll.dll';
Run Code Online (Sandbox Code Playgroud)
这是一个DLL示例代码:
library Project3;
// uses YourMethodIntf.pas
{$R *.res}
var AppMethod : IMyMethodInterface;
procedure SetAppMethodCallback(mmi : IMyMethodInterface); stdcall;
begin
AppMethod := mmi;
end;
procedure AnotherDllMethod();
begin
//here you can use AppMethod.MyMethod();
end;
exports
SetAppMethodCallback name 'SetMethodcallback';
begin
end.
Run Code Online (Sandbox Code Playgroud)
考虑到你的mmoobject(TMyMethodInterface)在你将AppMethoddll 设置为nil(或FreeLibrary dll)之前不会被销毁,所以要小心