CoInitialize() has not been called exceptions in C++

Nick X Tsui picture Nick X Tsui · Jun 13, 2013 · Viewed 17.9k times · Source

-My problem

I got CoInitialize has not been called exption.

-My project structure

Here is my porblem. I have a COM dll, MCLWrapper.dll developped with C#; I have a nother native C++ dll, ThorDetectorSwitch.dll that calls MCLWrapper.dll; And finally, I have a console application TDSTest.exe that calls ThorDetectorSwitch.dll. Basically, something like this:

TDSTest.exe (C++ console) -> ThorDetectorSwitch.dll (C++ native) -> MCLWrapper.dll (C#)


Code in TDSTest.exe that loads the ThorDetectorSwitch.dll:

HINSTANCE hInst = LoadLibrary(_T("C:\\TIS_Nick\\Hardware\\Devices\\ThorDetectorSwitch\\TDSTest\\TDSTest\\Debug\\Modules_Native\\ThorDetectorSwitch.dll"));

Constructor in ThorDetectorSwitch.cpp

ThorDetectorSwitch::ThorDetectorSwitch() : _mcSwitch(__uuidof(MCLControlClass))
{
    _A  = WstringToBSTR(L"A"); 
    _B  = WstringToBSTR(L"B");
    _C  = WstringToBSTR(L"C");
    _D  = WstringToBSTR(L"D");

    _deviceDetected = FALSE;
}

The break point hits the first parenthesis of the constructor of the ThorDetectorSwitch.dll above, but the exception occurred immediately if I hit F10 (one more step)

It jumps to

 hr = CoCreateInstance(rclsid, pOuter, dwClsContext, __uuidof(IUnknown), reinterpret_cast<void**>(&pIUnknown));

in the comip.h. The hr is simply "CoInitialize has not been called".

I have been thinking abou this porblem for days, and cannot figure out a solution. Anyone here can sharing any thoughts? Really appreciate it.

Answer

Reed Copsey picture Reed Copsey · Jun 13, 2013

Your COM dll requires you to be in Single-Threaded Apartment mode. You need to call CoInitialize prior to using it.

Add this to your .exe:

CoInitialize(nullptr); // NULL if using older VC++

HINSTANCE hInst = LoadLibrary(_T("C:\\TIS_Nick\\...