我有一个 dll,其中包含一个实现接口(interface)的类。该 dll 有一个返回接口(interface)的导出方法。
我可以成功显式加载 dll,但是当我尝试使用免费库时,出现访问冲突。我没有尝试使用隐式链接,因为我需要使用显式模式。
如果我只是加载库并立即释放,而不获取界面,则一切正常。
DLL
library Tef;
uses
uTTefFacade;
{$R *.res}
exports
CreateTef;
begin
end.
dll中的接口(interface):
type
ITefFacade = interface
['{77691DD1-C6E9-4F75-951F-BFA1468DC36C}']
function IniciarTransacao(AParam: TTefIniciarTransacaoParamDTO): TTefIniciarTransacaoResultDTO;
end;
dll 中的类:
type
TTefFacade = class (TInterfacedObject, ITefFacade)
private
function IniciarTransacao(AParam: TTefIniciarTransacaoParamDTO): TTefIniciarTransacaoResultDTO;
public
constructor Create;
destructor Free;
end;
function CreateTef: ITefFacade; export; stdcall;
function CreateTef: ITefFacade;
begin
Result := ITefFacade(TTefFacade.Create);
end;
执行程序:
procedure TForm1.FormCreate(Sender: TObject);
var
CreateTef: function: ITefFacade; stdcall;
begin
try
FTef := nil;
FHTef := LoadLibrary('Tef.dll');
if (FHTef > 0) then
begin
@CreateTef := GetProcAddress(FHTef, 'CreateTef');
if (@CreateTef <> nil) then
FTef := CreateTef;
end;
if (FTef = nil) then
ShowMessage('Error.');
except
on E: Exception do
ShowMessage('Erro: ' + E.Message);
end;
end;
在调用免费库时,发生访问冲突。
procedure TForm1.FormDestroy(Sender: TObject);
begin
FreeLibrary(FHTef);
end;
最佳答案
在释放 DLL 之前,您必须nil
FTef
引用。
接口(interface)背后的对象存在于 DLL 中,你应该尊重这一点。如果您尝试在不先释放接口(interface)的情况下卸载 DLL,则在卸载后访问对象时会出现问题(例如当 Delphi 超出范围时自动清空引用时)。
关于delphi - 访问冲突释放库,返回 dll 中类的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47702267/