我一直在编写一个 C++ 程序,在其中为 exe 文件创建快捷方式链接,为此我需要在开头编写 CoInitialize(0);
。没有它,代码就无法工作。有人可以帮助我知道为什么我们使用它吗?
我只是想知道为什么我们使用这个功能。
最佳答案
CoInitialize()
,以及扩展和更推荐的版本CoInitializeEx()
,用于初始化 COM当前线程的库:
Initializes the COM library on the current thread
...
New applications should call CoInitializeEx instead of CoInitialize.
必须为每个使用 COM 的线程调用它。
请注意,CoInitialize()
将并发模型标识为单线程单元 (STA),而使用 CoInitializeEx()
您可以自由地指定并发模型。
有关 COM 线程和其他相关问题的更多信息:Processes, Threads, and Apartments .
如果您不熟悉 COM (来自文档):
COM is a platform-independent, distributed, object-oriented system for creating binary software components that can interact. COM is the foundation technology for Microsoft's OLE (compound documents) and ActiveX (Internet-enabled components) technologies.
如果您的程序需要调用上述初始化函数之一,则意味着您直接使用 COM,或者您使用的任何库正在使用 COM。
请注意,每次成功调用 CoInitialize/Ex()
都必须与对 CoUninitialize()
的调用相匹配。 .
编辑:
正如 @IInspectable 所评论的,在线程上使用 COM 对象并不严格要求调用 CoInitialize/Ex()
。
但是,由于 COM 对象具有如上所述的线程要求,因此调用它可以确保当前线程使用正确的 COM 并发模型。
请参阅Why does CoCreateInstance work even though my thread never called CoInitialize? The curse of the implicit MTA .
关于c++ - 为什么使用CoInitialize(0);在 C++ 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74939070/