Search code examples
c++windowswinapiaudiocom

CoCreateInstance in the MMDevice API returns error code 0x800401F0


As in the title, I am getting an error code that is not in the documentation of CoCreateInstance. The specific error code is 0x800401F0.

Note: I am new to C++ and programming at this level in general. Trying to learn by building an audio visualization tool.

#include <stdio.h>
#include <Mmdeviceapi.h>

int CALLBACK WinMain(
  HINSTANCE hInstance,
  HINSTANCE hPrevInstance,
  LPSTR     lpCmdLine,
  int       nCmdShow
)
{
    const CLSID rclsid = __uuidof(MMDeviceEnumerator);
    const IID riid = __uuidof(IMMDeviceEnumerator);
    IMMDeviceEnumerator* pEnumerator;
    IMMDeviceCollection* pEndpoints;

    // Create a device enumerator
    HRESULT hr = CoCreateInstance(
        rclsid,
        NULL,
        CLSCTX_ALL,
        riid,
        reinterpret_cast<void **>(&pEnumerator)
    ); 
    if (FAILED(hr)) {
        printf("%x\n", hr);
    }
    // Create a collection of endpoints
    // pEnumerator->EnumAudioEndpoints(
    //  eCapture,
    //  DEVICE_STATE_ACTIVE,
    //  &pEndpoints
    // );

    // UINT deviceCount;
    // pEndpoints->GetCount(&deviceCount);
    // printf("%u\n", deviceCount);

    return 0;
}

Compilation gcc audio.cpp -lole32

I am running a 64-bit machine. Not sure if that may be part of the issue. Any suggestions?


Solution

  • The error code 0x800401F0 is CO_E_NOTINITIALIZED ("CoInitialize has not been called"). That suggests that you did not call CoInitialize() first.

    That is, a thread needs to call CoInitialize() (or CoInitializeEx()) before calling CoCreateInstance() or any other COM call. If you need graceful cleanup, you are supposed to release COM interface pointers, complete your COM activity, and call CoUninitialize() before exiting.