IMFActivate::ActivateObject return 错误代码 "CoInitialize has not been called."

IMFActivate::ActivateObject return error code "CoInitialize has not been called."

我在 Visual Studio 2013 年编写了一个简单的多媒体应用程序,我需要枚举连接到我的计算机的相机设备并创建一个媒体源对象 link 其中之一。我使用 Media Foundation SDK 并尝试 运行 此处的指南:https://msdn.microsoft.com/en-us/library/windows/desktop/dd940326(v=vs.85).aspx :

#include <Mfapi.h>
#include <mfidl.h>
#include <mfobjects.h>
#include <iostream>

#pragma comment(lib, "Mfplat")
#pragma comment(lib, "Mf")

template <class T> void SafeRelease(T **ppT) {
  if (*ppT) {
    (*ppT)->Release();
    *ppT = NULL;
  }
}

HRESULT CreateVideoDeviceSource(IMFMediaSource **ppSource) {
  *ppSource = NULL;

  IMFMediaSource *pSource = NULL;
  IMFAttributes *pAttributes = NULL;
  IMFActivate **ppDevices = NULL;

  // Create an attribute store to specify the enumeration parameters.
  HRESULT hr = MFCreateAttributes(&pAttributes, 1);
  if (FAILED(hr))
  {
    goto done;
  }

  // Source type: video capture devices
  hr = pAttributes->SetGUID(
    MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
    MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID
  );
  if (FAILED(hr))
  {
    goto done;
  }

  // Enumerate devices.
  UINT32 count;
  hr = MFEnumDeviceSources(pAttributes, &ppDevices, &count);
  if (FAILED(hr))
  {
    goto done;
  }

  if (count == 0)
  {
    hr = E_FAIL;
    goto done;
  }

  // Create the media source object.
  hr = ppDevices[0]->ActivateObject(IID_PPV_ARGS(&pSource));
  if (FAILED(hr))
  {
    std::cout << "Failed to create device object" << hr <<std::endl;
    goto done;
  }

  *ppSource = pSource;
  (*ppSource)->AddRef();

  DWORD chs;
  (*ppSource)->GetCharacteristics(&chs);
  std::cout << chs << std::endl;

 done:
   SafeRelease(&pAttributes);

   for (DWORD i = 0; i < count; i++)
   {
     SafeRelease(&ppDevices[i]);
   }
   CoTaskMemFree(ppDevices);
   SafeRelease(&pSource);
   return hr;
  }

int main(int argc, char* argv[]) {
  IMFMediaSource* ppSource;
  CreateVideoDeviceSource(&ppSource);
  std::cout << "END" << std::endl;

  return 0;
}

问题是这部分代码:

 // Create the media source object.
hr = ppDevices[0]->ActivateObject(IID_PPV_ARGS(&pSource));
if (FAILED(hr))
{
  goto done;
}

创建媒体源对象失败(返回的 HRESULT 为 0x800401F0 (CO_E_NOTINITIALIZED)--"CoInitialize 尚未被调用。 ")。错误代码是什么意思,可能是什么问题导致了失败?我使用的是 WIN8.1。

Com 库需要为每个线程初始化,通过

  • CoInitialize
  • CoInitializeEx
  • OleInitialize

取决于要在此线程中使用哪些服务。

在程序开始时为所有使用 COM 的线程执行此操作,并且不要忘记调用相应的 Uninitialize 函数