none
COM, C++/CLI, C# and CoInitialize()/CoUninitialize() RRS feed

  • Question

  • Hi all,

    I'm working on a project which makes use of COM in unmanaged C++. That unmanaged C++ is then wrapped in a managed C++ class. Finally, this managed C++ class is then consumed in a C# application. I'd like the unmanaged C++ and the wrapper to became a simple .NET dll

    What is the best way to handle the call(s) to CoInitialize()/CoUninitialize() for the COM being used in the unmanaged C++?

    I have the following options:
    - Add a call to CoInitialize() in the constructor for the unmanaged C++ class and a call to CoUninitialize() in the destructor.
    - Calling that functions each time a create a thread from C# trough a PInvoke call or trough a managed C++ wrapper.

    I prefer the first method: do anyone see any issue with that?
    Is there an easier way to do this?

    Thanks
    Thursday, March 18, 2010 11:11 AM

Answers

  • For threads created by the CLR, CoInitialize will be called already by the runtime. You only need to call it yourself if the C++ library creates any threads of its own.

    Mattias, C# MVP
    • Marked as answer by SamAgain Monday, March 29, 2010 3:01 AM
    Thursday, March 18, 2010 12:09 PM
    Moderator

All replies

  • For threads created by the CLR, CoInitialize will be called already by the runtime. You only need to call it yourself if the C++ library creates any threads of its own.

    Mattias, C# MVP
    • Marked as answer by SamAgain Monday, March 29, 2010 3:01 AM
    Thursday, March 18, 2010 12:09 PM
    Moderator
  • Thanks.

    But what is the best way to handle it in any alternate thread?!

    Monday, March 22, 2010 10:39 AM