Tony The Lion
Tony The Lion

Reputation: 63250

Call QueryInterface before CoCreateInstance?

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

Upvotes: 0

Views: 1080

Answers (2)

sharptooth
sharptooth

Reputation: 170509

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.

Upvotes: 1

ChrisW
ChrisW

Reputation: 56123

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.

Upvotes: 5

Related Questions