DLL中不能调用CoInitialize和CoInitializeEx

在项目中为了用API访问Wmi Object来实现命令wmic的功能,所以得使用COM库,使用COM库之前得初始化一些东西。

 1  m_hr = CoInitializeEx(0, COINIT_APARTMENTTHREADED);
 2     if (FAILED(m_hr))
 3     {
 4         std::ostringstream errorStream;
 5         errorStream << "Failed to initialize COM library. Error code = 0x" << std::hex << m_hr << std::endl;
 6         throw WmiException(errorStream.str());
 7     }
 8 
 9     m_hr = CoInitializeSecurity(
10         NULL,                        // Security descriptor    
11         -1,                          // COM negotiates authentication service
12         NULL,                        // Authentication services
13         NULL,                        // Reserved
14         RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication level for proxies
15         RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation level for proxies
16         NULL,                        // Authentication info
17         EOAC_NONE,                   // Additional capabilities of the client or server
18         NULL);                       // Reserved
19 
20     if (FAILED(m_hr))
21     {
22         std::ostringstream errorStream;
23         errorStream << "Failed to initialize security. Error code = 0x" << std::hex << m_hr << std::endl;
24         CoUninitialize();
25         throw WmiException(errorStream.str());
26     }

上面的代码在单元测试中运行良好,但是集成测试的时候就出现了问题,因为这段代码被放到了DLL中被调用,所以就错了。

因为加载DLL的时候会自动初始化COM库。所以再初始化就会报错,返回错误码:0x80010106 ----- Cannot change thread mode after it is set

要解决很简单,就是根据错误提示,不用初始化了,把代码中的两个初始化函数删除就可以了

references:

https://social.msdn.microsoft.com/Forums/vstudio/en-US/e1bc9fe4-d985-473a-88f7-ef2ed47f77b3/native-c-return-hresult-0x80010106-cannot-change-thread-mode-after-it-is-set-in-net-web?forum=vclanguage

http://stackoverflow.com/questions/11708497/com-library-initilization-failed-with-code-0x80010106-in-c-sharp

http://stackoverflow.com/questions/2453973/using-dll-that-using-com-in-c-sharp

https://msdn.microsoft.com/en-us/library/aa394582(v=vs.85).aspx

原文地址:https://www.cnblogs.com/foohack/p/6645919.html