سؤال

How to free IDispatch COM Object in Delphi? Do I have to?

type
 IUtility = interface(IDispatch);

var
  obj: IUtility;

begin
  obj := CreateOleObject("Utility") as IUtility;


  // doesnot work
  VariantClear(obj);
end;
هل كانت مفيدة؟

المحلول

IDispatch is just like all other interfaces. When an object implementing it sees its reference count reach zero, it will destroy itself.

Delphi automatically inserts code to call _AddRef and _Release on interfaces at the appropriate times, including when a variable goes out of scope. Thus, at the end of your function, obj will go out of scope, and the compiler will automatically insert code to essentially do if not Assigned(obj) then obj._Release.

Since it happens automatically, you don't need to do anything yourself. However, if you want to relinquish control of an interfaced object earlier than the natural end of the scope, you can simply clear the variable by assigning nil.

obj := nil;

Your obj variable is not of type Variant, which is why it's wrong to call VariantClear on it.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top