Check COM pointers for equality(检查 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;
}
更新
- 添加了对 Release 的调用,以减少引用计数.感谢您的好评.
- 您也可以使用 ComPtr 来完成这项工作.请查看 MSDN.
这篇关于检查 COM 指针是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检查 COM 指针是否相等


基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01