Why do IUnknown* pointers retrieved through different interfaces of the same COM object have the same value?

与世无争的帅哥 提交于 2019-12-07 13:17:21

问题


I have the following hierarchy of COM interfaces and a class implementing them:

interface IX : public IUnknown{};
interface IY : public IUnknown{};
class CA: public IX, public IY{};

Here class CA effectively inherits from IUnknown twice.

We know there are two vtable pointers in class CA - one is pointed to IX and another is pointed to IY. So IUnknown stored in the IX subobject is different from IUnknown stored in the IY subobject.

Yet when we call IX::QueryInterface() or IY::QueryInterface() on the same object and query IUnknown we get identical IUnknown* pointers.

Why does it happen?


回答1:


That's so called "object identity" requirement that states that whenever you request IUnknown from two objects you get distinct pointers if those are distinct objects and equal pointers if that's the same object.

Every QueryInterface() implementation must fulfill this requirement. This is usually done by choosing which one IUnknown to return and sticking to it:

HRESULT CA::QueryInterface( REFIID iid, void** ppv )
{
    if( iid == __uuidof( IUnknown ) ) {
        // Explicitly cast to one of base class subobjects.
        // Doesn't matter which one is chosen - it just has to be
        // the same base class subobject each time IUnknown is requested.
       IUnknown* selected = static_cast<IX*>( this );
       *ppv = selected;
       AddRef();
       return S_OK;
    } else {
       continue for other interfaces
    }
}


来源:https://stackoverflow.com/questions/5753000/why-do-iunknown-pointers-retrieved-through-different-interfaces-of-the-same-com

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!