Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to Free IDispatch in Delphi

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;
like image 675
justyy Avatar asked Jan 27 '26 14:01

justyy


1 Answers

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.

like image 117
Rob Kennedy Avatar answered Jan 31 '26 20:01

Rob Kennedy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!