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

偶尔善良 提交于 2019-12-23 07:26:37

问题


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


来源:https://stackoverflow.com/questions/17076441/coinitialize-has-not-been-called-exceptions-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!