Search code examples
c++visual-studio-2008dllcom

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.


Solution

  • 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.