问题描述
以下是创建COM对象的代码示例:
Here's a code sample creating a COM object:
CComPtr<IBaseFilter> pFilter;
auto hr = CoCreateInstance(CLSID_DMOWrapperFilter, NULL,
CLSCTX_INPROC_SERVER, IID_IBaseFilter, reinterpret_cast<void**>(&pFilter));
我看过某个地方检查 CoCreateInstance $ c> succeeded应该像这样:
I've seen somewhere that checking if CoCreateInstance()
succeeded should look like this:
if (SUCCEEDED(hr) && pFilter != nullptr)
{
// code goes here
}
只检查 hr
?这不够吗?我应该检查 filter!= nullptr
?
What if I would check only hr
? Wouldn't it be enough? Should I also check that filter != nullptr
?
//would this be enough?
if (SUCCEEDED(hr))
{
// code goes here
}
此问题还涉及其他COM方法,如 QueryInterface()
。
This question also concerns other COM methods like QueryInterface()
.
推荐答案
从 CoCreateInstance
获得 S_OK
结果, c $ c> NULL 接口指针,因此您不需要额外检查它。为了使它更可靠,能够及早发现问题,你可能想使用 ATLASSERT
与 NULL
。这不会在版本生成中生成代码,但如果出现任何问题(尤其是您稍后编辑或复制粘贴代码并更改获取指针的逻辑),则会在调试中生成早期警告。
Having S_OK
result from CoCreateInstance
you are guaranteed to get a non-NULL
interface pointer, so you don't need to check it additionally. To make it more reliable and be able to detect issues early, you might want to use ATLASSERT
there to compare against NULL
. This does not produce code in release builds, but generates an early warning in debug if anything goes wrong (esp. you edit or copy paste code later and change the logic of obtaining the pointer.
CComPtr<IBaseFilter> pFilter;
HRESULT hr = CoCreateInstance(CLSID_DMOWrapperFilter, NULL, CLSCTX_INPROC_SERVER,
IID_IBaseFilter, reinterpret_cast<VOID**>(&pFilter));
if(SUCCEEDED(hr))
{
ATLASSERT(pFilter); // hr is of the interest because might explain failure
// pFilter is expected to be non-NULL in case of S_OK
const CComQIPtr<IDMOWrapperFilter> pDmoWrapperFilter = pFilter;
if(pDmoWrapperFilter)
{
// We're not really interested in QueryInterface's HRESULT since it's
// either S_OK or E_NOINTERFACE, hr will typically explain nothing special.
// More important is whether we finally obtained the pointer or not
}
}
这篇关于处理CoCreateInstance返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!