本文介绍了处理 CoCreateInstance 返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是创建 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() 是否成功应该是这样的:

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 结果,你保证得到一个非NULL代码>接口指针,所以你不需要额外检查它.为了使其更可靠并能够及早发现问题,您可能希望在那里使用 ATLASSERTNULL 进行比较.这不会在发布版本中生成代码,但如果出现任何问题(尤其是您稍后编辑或复制粘贴代码并更改获取指针的逻辑),则会在调试中生成早期警告.

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 返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 13:03