IUnknown Interface
The IUnknown
interface is the base interface from which all COM (Component Object Model) interfaces are derived. It provides the fundamental mechanisms for reference counting and querying for other interfaces supported by an object.
Every COM object must implement IUnknown
. This interface guarantees that you can always discover the identity and capabilities of a COM object.
Methods
-
QueryInterface
HRESULT QueryInterface(REFIID riid, void **ppvObject);
Retrieves pointers to supported interfaces on an object.
riid
: The interface identifier (IID) for the interface to be retrieved.ppvObject
: A pointer to a pointer to receive the interface pointer.
Return Value: Returns
S_OK
if the interface is supported,E_NOINTERFACE
otherwise. -
AddRef
ULONG AddRef(void);
Increments the reference count for an object. The object should only be deleted when its reference count is zero.
Return Value: The new reference count.
-
Release
ULONG Release(void);
Decrements the reference count for an object. If the reference count drops to zero, the object is destroyed.
Return Value: The new reference count.
Remarks
IUnknown
is central to the COM model. Its three methods are fundamental:
QueryInterface
: Allows clients to ask an object if it supports a particular interface (identified by its GUID, or IID).AddRef
: Used to increment the reference count of an object. Clients call this when they obtain a pointer to an interface and want to ensure the object stays alive.Release
: Used to decrement the reference count. Clients call this when they are finished with an interface pointer. When the count reaches zero, the object typically destroys itself.
Proper management of reference counts is crucial to prevent memory leaks and dangling pointers in COM programming.
IUnknown
, directly or indirectly. This ensures that all COM objects support these core functionalities.