gpt4 book ai didi

delphi - 访问冲突释放库,该库返回 dll 中类的接口(interface)

转载 作者:行者123 更新时间:2023-12-03 19:24:54 29 4
gpt4 key购买 nike

我有一个 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;

最佳答案

您必须 nil FTef在释放 DLL 之前引用。

接口(interface)背后的对象位于 DLL 中,您应该尊重这一点。如果在不释放接口(interface)的情况下尝试卸载DLL,那么在卸载后访问对象时会出现问题(例如Delphi在超出范围时自动取消引用时)。

关于delphi - 访问冲突释放库,该库返回 dll 中类的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47702267/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com