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 interface querying.

Summary

All COM objects must implement the IUnknown interface. It provides three methods:

  • QueryInterface: Retrieves pointers to other interfaces on an object.
  • AddRef: Increments the reference count for an object.
  • Release: Decrements the reference count for an object.

Interface Definition


interface DECLSPEC_UUID_ x IUnknown
{
    // Retrieve a pointer to a specified interface.
    // Returns S_OK if the interface is supported, E_NOINTERFACE otherwise.
    virtual HRESULT STDMETHODCALLTYPE QueryInterface(
        REFIID riid,
        _Outptr_ void **ppvObject) = 0;

    // Increment the reference count.
    // Returns the new reference count.
    virtual ULONG STDMETHODCALLTYPE AddRef( void) = 0;

    // Decrement the reference count.
    // Returns the new reference count.
    // When the reference count reaches zero, the object is destroyed.
    virtual ULONG STDMETHODCALLTYPE Release( void) = 0;
};
                

Methods

QueryInterface

Syntax


HRESULT QueryInterface(
    REFIID riid,
    _Outptr_ void **ppvObject);
                

Parameters

  • riid: [in] The interface identifier (IID) of the requested interface.
  • ppvObject: [out] Pointer to the queried interface pointer. This parameter can be NULL.

Return Value

If the method succeeds, the return value is S_OK. Otherwise, E_NOINTERFACE.

AddRef

Syntax


ULONG AddRef();
                

Parameters

This method takes no parameters.

Return Value

The return value is the new reference count of the object.

Release

Syntax


ULONG Release();
                

Parameters

This method takes no parameters.

Return Value

The return value is the new reference count of the object. It is used for debugging and testing purposes only. The application should not rely on this value for any other purpose.

Remarks

Every COM object must implement IUnknown. The QueryInterface method is crucial for dynamic interface discovery and type checking. AddRef and Release implement the reference counting mechanism, ensuring that an object is deallocated only when no longer in use.

See Also