问题描述
如果我有两个 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 以外的接口(即使相同的接口通过相同的指针)必须返回相同的指针值.
所以正确的代码是
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 指针是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!