检查COM指针是否相等 [英] Check COM pointers for equality

查看:155
本文介绍了检查COM指针是否相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个COM接口指针(即ID3D11Texture2D),并且我想检查他们是否是相同的底层类实例,我可以直接比较两个指针相等吗?我已经看过代码,我们在比较之前将它转换为别的东西,所以要确认。

If I have two COM interface pointers (i.e. ID3D11Texture2D), and I want to check if they are the same underlying class instance, can I compare the two pointers directly for equality? I have seen code where we cast it to something else before the comparison is done, so wanted to confirm.

BOOL IsEqual (ID3D11Texture2D *pTexture1, ID3D11Texture2D *pTexture2)
{
    if (pTexture1 == pTexture2)
    {
        return true;
    }
    else
    {
        return false;
    }
} 

谢谢。

推荐答案

正确的COM方式是通过IUnknown查询接口。 此处的备注的引语在MSDN中:

The correct COM way to do this is to query interface with IUnknown. A quote from the remarks here in MSDN:


对于任何一个对象,对象接口的任何
上的IUnknown接口的特定查询必须总是返回相同的指针值。
这使得客户端可以通过调用具有IID_IUnknown的QueryInterface和比较结果的
来确定两个指针是否指向
同一组件。特别不是这样的情况,对于除了IUnknown以外的接口(即使通过
的同一个接口,相同的指针)查询
必须返回相同的指针值。

For any one object, a specific query for the IUnknown interface on any of the object's interfaces must always return the same pointer value. This enables a client to determine whether two pointers point to the same component by calling QueryInterface with IID_IUnknown and comparing the results. It is specifically not the case that queries for interfaces other than IUnknown (even the same interface through the same pointer) must return the same pointer value.

所以正确的代码是

BOOL IsEqual (ID3D11Texture2D *pTexture1, ID3D11Texture2D *pTexture2)
{
    IUnknown *u1, *u2;

    pTexture1->QueryInterface(IID_IUnknown, &u1);
    pTexture2->QueryInterface(IID_IUnknown, &u2);

    BOOL areSame = u1 == u2;
    u1->Release();
    u2->Release();

    return areSame;
}

更新


  1. 添加了对发布的调用,以减少引用计数。感谢您的好评。

  2. 您也可以使用ComPtr完成这项工作。请查看MSDN。

这篇关于检查COM指针是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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