Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

com

dllimport

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

like image 702
Nick X Tsui Avatar asked Jun 12 '13 22:06

Nick X Tsui


1 Answers

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\\...
like image 61
Reed Copsey Avatar answered Nov 05 '22 21:11

Reed Copsey