A. Boz A. Boz - 1 month ago 10
C++ Question

CoCreateInstance dont work

I tried to make a Bitmap with direct2d.
The problem is the function CoCreateInstance(...) it wont work

HRESULT Renderer::InitImagingFactory()
{
if (FAILED(CoInitializeEx(NULL, COINIT_MULTITHREADED))) return E_FAIL;


if (FAILED(CoCreateInstance(
CLSID_WICImagingFactory,
NULL,
CLSCTX_INPROC_SERVER,
IID_IWICImagingFactory,
reinterpret_cast<void **>(&m_imagingfactory)))) return E_FAIL;

return S_OK;
}

Answer

There's two main reasons you could be hitting this.

(1) You need to initialize COM before calling this function. For classic Win32 desktop apps, you'd do this with CoInitialize or CoInitializeEx. For Windows Runtime platforms you'd use Windows::Foundation::Initialize.

(2) You need to make sure you have _WIN32_WINNT set correctly for your target platform--see Using the Windows Headers.

For a classic Win32 desktop app, you probably want to use the following which initializes WIC2 on platforms that support it or WIC1 otherwise--code found in DirectXTex and DirectXTK's WICTextureLoader.

namespace
{
    bool g_WIC2 = false;
}

bool _IsWIC2()
{
    return g_WIC2;
}

IWICImagingFactory* _GetWIC()
{
    static INIT_ONCE s_initOnce = INIT_ONCE_STATIC_INIT;

    IWICImagingFactory* factory = nullptr;
    InitOnceExecuteOnce(&s_initOnce,
        [](PINIT_ONCE, PVOID, PVOID *factory) -> BOOL
        {
        #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE)
            HRESULT hr = CoCreateInstance(
                CLSID_WICImagingFactory2,
                nullptr,
                CLSCTX_INPROC_SERVER,
                __uuidof(IWICImagingFactory2),
                factory
                );

            if ( SUCCEEDED(hr) )
            {
                // WIC2 is available on Windows 10, Windows 8.x, and Windows 7 SP1 with KB 2670838 installed
                g_WIC2 = true;
                return TRUE;
            }
            else
            {
                hr = CoCreateInstance(
                    CLSID_WICImagingFactory1,
                    nullptr,
                    CLSCTX_INPROC_SERVER,
                    __uuidof(IWICImagingFactory),
                    factory
                    );
                return SUCCEEDED(hr) ? TRUE : FALSE;
            }
        #else
            return SUCCEEDED( CoCreateInstance(
                CLSID_WICImagingFactory,
                nullptr,
                CLSCTX_INPROC_SERVER,
                __uuidof(IWICImagingFactory),
                factory) ) ? TRUE : FALSE;
        #endif
        }, nullptr, reinterpret_cast<LPVOID*>(&factory));

    return factory;
}

This uses the InitOnceExecuteOnce pattern to ensure it's thread-safe.

Comments