在項目中為了用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