开发者

Call QueryInterface before CoCreateInstance?

开发者 https://www.devze.com 2023-01-06 01:54 出处:网络
Is the above possible? Can I do this: IUnknown *punk; punk->QueryInterface(IID_MyInterface, (void**)&m_pMyInterface);

Is the above possible?

Can I do this:

IUnknown *punk;

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

I th开发者_JAVA百科ought that this would tell me if the MyInterface is supported m_pMyInterface...


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消