gpt4 book ai didi

delphi - 我应该使用哪一个来释放 COM 对象?

转载 作者:行者123 更新时间:2023-12-03 18:16:31 25 4
gpt4 key购买 nike

我有一个 COM 类,它看起来像这样:

  TRadioTracer = class(TAutoObject, IRadioTracer)

现在,我可以做到
var
obj: TRadioTracer;
begin
obj := TRadioTracer.Create;
// some other code
obj.Free;
obj.CleanupInstance;
obj.FreeInstance;
end;

这些来自 System.pas
procedure TObject.FreeInstance;
begin
CleanupInstance;
_FreeMem(Pointer(Self));
end;

procedure TObject.CleanupInstance;
{$IFDEF PUREPASCAL}
var
ClassPtr: TClass;
InitTable: Pointer;
begin
{$IFDEF WEAKREF}
_CleanupInstance(Self);
{$ENDIF}
ClassPtr := ClassType;
repeat
InitTable := PPointer(PByte(ClassPtr) + vmtInitTable)^;
if InitTable <> nil then
_FinalizeRecord(Self, InitTable);
ClassPtr := ClassPtr.ClassParent;
until ClassPtr = nil;
TMonitor.Destroy(Self);
end;
{$ELSE !PUREPASCAL}
// some other code

procedure TObject.Free;
begin
// under ARC, this method isn't actually called since the compiler translates
// the call to be a mere nil assignment to the instance variable, which then calls _InstClear
{$IFNDEF AUTOREFCOUNT}
if Self <> nil then
Destroy;
{$ENDIF}
end;

我应该使用哪一个来释放 COM 对象?

最佳答案

使用接口(interface)类型来存储对对象的引用。一旦没有对它的引用,它将被销毁:

var
obj: IRadioTracer;
begin
obj := TRadioTracer.Create;
obj.DoThings;
end; // obj will be freed here automatically

当您在不同的应用程序中或通过 TAutoObjectFactory 使用 COM-Object 时那么你只会知道接口(interface)类型。您将无法访问具体的类类型。这就是为什么在这里更喜欢接口(interface)类型而不是类类型的另一个原因。

如果您使用类类型来引用您需要调用的对象 Free摧毁它。

关于delphi - 我应该使用哪一个来释放 COM 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33019963/

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