CoInitialize() has not been called exceptions in C

2019-06-17 08:55发布

问题:

-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.

回答1:

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\\...