Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using IXMLDocument inside a DLL needs CoInitialize?

Tags:

winapi

delphi

Is there ever a reason to use CoInitialize inside my DLL function when using IXMLDocument (msxml wrapper)? (or Other com object for that matter)

Is the calling application/thread responsible for calling CoInitialize/CoUninitialize?

What if I use ComObj inside my DLL which automatically calls CoInitialize in its initialization section and CoUninitialize in its finalization section?

like image 299
zig Avatar asked Dec 17 '15 14:12

zig


1 Answers

Is the calling application/thread responsible for calling CoInitialize/CoUninitialize?

Yes. As a general rule, the creator of a thread must be responsible for initializing COM. Which means that the functions that you expose from your DLL should not initialize COM for the thread on which they were called.

The reason being that if you take responsibility for initializing COM in the thread that calls the DLL, then that places an unreasonable constraint on the creator of that thread. What if the creator of the thread needs to perform another action that requires COM to be initialized? The standard practise is that the DLL specifies COM initialization as one of its requirements. In the documentation for your DLL, state that the caller must initialize COM.

More details here: Things you shouldn't do, part 2: Dlls can't ever call CoInitialize* on the application’s thread.

That's why you should not initialize COM in your DLL on the caller's thread. There's even more reason not to initialize COM in an initialization section. Initialization sections are executed inside the DLL's DllMain. There are very few things that you are allowed to call inside DllMain, COM functions not being on the list of allowed actions. For more details: Some reasons not to do anything scary in your DllMain, part 3.

What if I use ComObj inside my DLL which automatically calls CoInitialize in its initialization section and CoUninitialize in its finalization section?

The ComObj unit does not do that. For a DLL, the COM initializing code that you refer to is suppressed. Including ComObj will force COM to be initialized in an executable project, but not in a library.

like image 102
David Heffernan Avatar answered Oct 16 '22 14:10

David Heffernan