All COM interfaces must implement IUnknown :
IUnknown = interface function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; end;
IUnknown provides two services. First of all, QueryInterface allows clients to get other interfaces that an object can implement. The second service is life cycle management.
Each time you refer to a COM object, you are responsible for calling _AddRef . Each time you refuse a reference to a COM object, you get a contract to call _Release .
The canonical implementation of _AddRef and _Release intended to ensure that the executing object maintains a reference counter variable, which increases and decreases when links are received and released. If the _Release call sets this reference count to 0, the object destroys itself.
The Delphi interface implementation manages the _AddRef and _Release on your behalf. When you assign an interface variable, the compiler emits code that:
- Calls
_Release on the interface the variable used to talk about if it really referred to something. - Calls
_AddRef on the interface to which the variable now refers.
The compiler also arranges _Release for the call whenever the variable leaves the scope.
This means that you do not need to take any special steps to ensure that your COM objects are destroyed. Naturally, they will be destroyed when the last reference to the object leaves the area.
If, however, you want to destroy the object ahead of time, then you simply assign nil variable holding the interface. Please note that this of course assumes that no other links are supported on this interface.
David heffernan
source share