简体   繁体   中英

Using IXMLDocument inside a DLL needs CoInitialize?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM