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 指针是否相等
基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01