Home > Blockchain >  Why use CoInitialize(0); in C
Why use CoInitialize(0); in C

Time:01-02

I have been writing a C program where I am creating a shortcut link for an exe file, and to do that I need to write the CoInitialize(0); at the starting. And without it the code does not work. Can someone help me to know why we use it?

I just want to know why we use this function.

CodePudding user response:

CoInitialize(), and the extended and more recommended version CoInitializeEx(), are used to initialize the COM library for the current thread:

Initializes the COM library on the current thread
...
New applications should call CoInitializeEx instead of CoInitialize.

It has to be called for each thread that uses COM.

Note that CoInitialize() identifies the concurrency model as single-thread apartment (STA), whereas with CoInitializeEx() you have the freedom to specify the concurrency model.

More about COM threads and other related issues: Processes, Threads, and Apartments.

In case you are not familiar with COM (from the documentation):

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.

If your program requires calling one of the initialization functions above, it means that either you directly, or any library you use, are using COM.

Note that each successful call to CoInitialize/Ex() must be matched with a call to CoUninitialize().


Edit:

As @IInspectable commented, using a COM object on a thread does not strictly require calling CoInitialize/Ex().

But, since COM objects have threading requirements as noted above, calling it ensures that the current thread uses the proper COM concurrency model.
See Why does CoCreateInstance work even though my thread never called CoInitialize? The curse of the implicit MTA.

  • Related