Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

COM Initialization and Use in Win32 C++ DLL

I am writing a Win32 C++ DLL that uses the COM to query WMI. How can I programmatically determine if COM has already been initialized? Thanks.

like image 742
Jim Fell Avatar asked Dec 15 '10 22:12

Jim Fell


2 Answers

Mark Ransom is right
the straightforward, clean and simple solution is to require COM initialization by the caller.

Ugly hack
You can try your first call - likely CoCreateInstance, and if it returns CO_E_NOTINITIALIZED, run CoInitialize yourself (and don't forget to uninit in that case)

However, it is still problematic to "inject" a CoInitialize into a caller thread from a DLL. So there's a

Clean Solution
Let the DLL create a worker thread (which means the DLL needs Init and Teardown calls), CoInitializeEx in this thread yourself, and move all the COM calls to that separate thread.

like image 200
peterchen Avatar answered Oct 21 '22 03:10

peterchen


The easiest way is not to bother, just make it a requirement of anybody using your DLL that they initialize COM first. Otherwise you run the risk of messing up their own initialization if they perform it after yours.

On the other hand if your flags to CoInitializeEx match those of the application, you should be fine. From the CoInitializeEx documentation:

Multiple calls to CoInitializeEx by the same thread are allowed as long as they pass the same concurrency flag, but subsequent valid calls return S_FALSE.

like image 28
Mark Ransom Avatar answered Oct 21 '22 03:10

Mark Ransom