为什么通过同一个COM对象的不同接口检索到的IUnknown *指针具有相同的值? [英] Why do IUnknown* pointers retrieved through different interfaces of the same COM object have the same value?

查看:127
本文介绍了为什么通过同一个COM对象的不同接口检索到的IUnknown *指针具有相同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下层次的COM接口和实现它们的类:

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

这里 class CA 有效地继承自 IUnknown 两次。



我们知道 class CA中有两个vtable指针 - 一个指向 IX ,另一个指向 IY 。因此,存储在 IX 子对象中的 IUnknown 不同于 IUnknown 然而,当我们调用 IX :: QueryInterface()时,我们可以使用 IY



<在同一对象和查询 IUnknown 上的
IY :: QueryInterface() IUnknown * 指针。



为什么会发生?

解决方案

这就是所谓的对象标识要求,它声明每当你从两个对象请求 IUnknown 时,如果这两个对象是相同的对象,那么它们是不同的对象,并且是相同的指针。 / p>

每个 QueryInterface()实现必须满足此要求。这通常是通过选择 IUnknown 返回并保留的

  HRESULT CA :: QueryInterface(REFIID iid,void ** ppv)
{
if iid == __uuidof(IUnknown)){
//显式转换为基类子对象之一。
//无论选择哪一个 - 它只需要
//每次请求IUnknown时都使用相同的基类子对象。
IUnknown * selected = static_cast< IX *(this);
* ppv = selected;
AddRef();
return S_OK;
} else {
continue for other interfaces
}
}


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?

解决方案

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

这篇关于为什么通过同一个COM对象的不同接口检索到的IUnknown *指针具有相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆