为什么通过同一 COM 对象的不同接口检索的 IUnknown* 指针具有相同的值?

发布于 2024-11-03 09:18:18 字数 594 浏览 1 评论 0原文

我有以下 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 与存储在 IY 子对象中的 IUnknown 不同。

然而,当我们对同一对象调用 IX::QueryInterface()IY::QueryInterface() 并查询 IUnknown 时,我们会得到相同的 IUnknown* 指针。

为什么会发生这种情况?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

人事已非 2024-11-10 09:18:18

这就是所谓的“对象标识”要求 指出,每当您从两个对象请求 IUnknown 时,如果它们是不同的对象,您将获得不同的指针;如果它们是同一对象,您将获得相等的指针。

每个 QueryInterface() 实现都必须满足此要求。这通常是通过选择要返回的 IUnknown 并坚持使用它来完成的:

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

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
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文