Using the IUnknown Interface

[This is preliminary documentation and subject to change.]

The IUnknown interface is the base interface for all Component Object Model (COM) interfaces exposed by COM objects. The COM objects implemented by CIMOM, WBEM providers, and event consumers expose one or more interfaces specified in the CIMOM API. For example, WBEM class providers implement a COM object that includes the IWbemProviderInit and IWbemServices interfaces.

IUnknown manages the lifespan of the COM object and handles client requests for access. To manage the COM object's lifespan, IUnknown maintains what is known as a reference count. The reference count is a tally of the number of active clients of a particular interface. Only when all of the reference counts for all of the interfaces exposed by a COM object reach zero can the object be deleted and its memory safely freed.The methods that support lifespan management are:

·    AddRef

·    Release

The third method of IUnknown, QueryInterface, is used to handle client access to the COM object. Clients gain access to a COM object by retrieving a pointer to one of the interfaces implemented by the object. To gain access to a particular interface, a client calls QueryInterface and sets the riid parameter to the identifier of the desired interface.

If this interface is not implemented by the COM object, QueryInterface returns the error value E_NOINTERFACE. If the interface is implemented by the object, QueryInterface calls AddRef to increment the reference count and returns a pointer to the interface in the ppv parameter.

Whenever a caller receives an interface pointer as an output parameter to a method, the caller must call the interface's AddRef method before calling any of the other methods. Receiving an interface pointer through QueryInterface is an exception to this rule because QueryInterface automatically calls AddRef as part of its implementation.

Whenever a user of an interface is finished with that interface, it must call Release.

Because that AddRef and Release are not required to return accurate values, callers of these methods should not use the return values to determine whether or not the COM object is still valid. Due to the concurrent use of objects by multiple threads, the reference count can easily be altered while it is being examined.