views:

148

answers:

3

IUnknown::QueryInterface() is passed a void** parameter denoting an address where to put the retrieved interface.

STDMETHOD QueryInterface(/* [in] */ REFIID riid, /* [iid_is][out] */ void** ppvObject)

Should the implementation of QueryInterface() check this pointer for being null (and then immediately return E_POINTER) or just write there?

I've seen a lot of COM-related code and almost everywhere no check is performed. Hypothetically someone could of course pass null pointer as this parameter, but is such check really needed?

+3  A: 

You (the caller) don't need to check the pointer for not being NULL.

However, you should check the returned HRESULT. The method will return E_POINTER if the output pointer is NULL and E_NOINTERFACE if the interface is unsupported.


The callee should check the pointer for not being NULL and return E_POINTER if it is NULL:

MSDN: Return Value:

This method returns S_OK if the interface is supported, and E_NOINTERFACE otherwise. If ppvObject is NULL, this method returns E_POINTER.

Mehrdad Afshari
A: 

According to the MSDN docs, QueryInterface either returns S_OK, in which case the out parameter will be set correctly. Or it returns E_NOINTERFACE, in which case the out parameter won't be set.

It will return E_POINTER if the void** you pass in is NULL.

I wouldn't bother checking for null, rather I'd check the return value from IUnknown::QueryInterface

There's probably no harm in checking for null, but given the guarantees of the interface it seems like a redundant check.

Glen
A: 

It depends on what kind of COM object you are QI'ing (Or which app is hosting you). Most of the time just checking the HRESULT should be enough. If you are dealing with 3rd party objects (Explorer replacement etc) you should probably also check for NULL. Explorer does this, and therefore you need to also if you want to avoid crashes in buggy extensions:

Anders

related questions