tags:

views:

39

answers:

2

Is the above possible?

Can I do this:

IUnknown *punk;

punk->QueryInterface(IID_MyInterface, (void**)&m_pMyInterface);

I thought that this would tell me if the MyInterface is supported m_pMyInterface...

+5  A: 

If you really mean what you've written above, then no: because your punk is an uninitialized pointer.

Normally you need to call CoCreateInstance to create an instance of something; after that you can call QueryInterface on that instance, to ask what interface[s] it supports.

ChrisW
so what if the CoCreateInstance return E_NOINTERFACE, what do I do then?
Tony
@Tony That means that the specified class doesn't support that interface: so if you still want to create an instance, either specify a different class or specify a different interface.
ChrisW
@Tony: Ask CoCreateInstance to return IID_IUnknown, and then do QueryInterface.
Sergius
+1  A: 

You can't do that. The proposed snippet would test if the object pointed to by punk supports the interface with IID_MyInterface and if it does support the interface pointer would be retrieved into m_pMyInterface and AddRef() would have been called on the pointer retrieved. Since punk in uninitialized it doen't point to any valid object so trying to call QueryInterface() would result in undefined behavior - your program would likely crash.

In order to test if the object pointed to by m_pMyInterface supports the interface with IID_MyInterface you would need to do the following:

IUnknown* punk;
HRESULT hr = m_pMyInterface->QueryInterface(IID_MyInterface, (void**)&punk);
if( SUCCEEDED( hr ) ) {
   //the interface is supported - don't forget that AddRef() has been called
} else {
   //the interface is not supported
}

The latter could only be done if m_pMyInterface already pointed to a live COM object.

sharptooth