DLL中不能调用CoInitialize和CoInitializeEx
调用 不能 dll
2023-09-11 14:19:35 时间
在项目中为了用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
相关文章
- 【手记】走近科学之为什么JObject不能调用LINQ扩展方法
- 网络编程 -- RPC实现原理 -- RPC -- 迭代版本V2 -- 本地方法调用 整合 Spring
- 《Hack与HHVM权威指南》——1.4.3 调用PHP代码
- Qt调用动态链接库ControlCAN.dll实例
- C++和C#相互调用COM组件的方法简介
- Spring开发 - 通过实现ApplicationContextAware在Servlet中调用注解的Service
- onInterceptTouchEvent和onTouchEvent调用关系详解
- SwiftUI 调用摄像头并拍摄照片camera UIImagePickerController
- tensorflow1.x——如何在python多线程中调用同一个session会话
- Perl调用外部命令(其他脚本、系统命令)的方法和区别
- 解决关闭窗口,C#报错"在创建窗口句柄之前,不能在控件上调用 Invoke 或 BeginInvoke"
- MSP430WARE++的使用2:RSP1 driver的调用方法
- grpc(4):使用 golang 调用consul api 接口,注册user-tomcat服务
- 用Entityframework 调用Mysql时,datetime格式插入不进去数据库的解决办法。
- C#调用user32.dll Win32的API函数