0

I'm implementing a C++ library that wraps a COM library (IMAPI) to more easily provide the functionality throughout our applications. It contains wrapper classes for the various interfaces of IMAPI. These are instantiated in the GUI thread of a client application to get information about the drives and their current medium. However, these objects also have functions to e.g. write data to a medium, which is a blocking function call.

Usually I would simply put this blocking function call onto another thread and execute it asynchronous to avoid blocking the GUI. However, since the COM objects were created in the GUI thread, which is initialized with COINIT_APARTMENTTHREADED (STA), this is not possible.

How do I best handle this in my shared library so that its clients do not have to worry about these details? Is the best thing to do to create a thread that belongs to my library that is initialized with COINIT_MULTITHREADED and is responsible for the creation of the COM objects?

Robert
  • 767
  • 8
  • 17
  • If you prefer to avoid blocking completely, create a side STA (worker thread) and manage IMAPI from there. Your outer COM object in the shared library would queue requests from higher level application and return immediately without blocking. – Roman R. Jan 14 '16 at 15:36
  • I was thinking about something like that, too. However, I was not happy with the overhead that creates, while the problem could be solved so easy if not for COM (by running blocking function in another thread). I'm currently changing the initialization of the COM objects in my library using a temporary thread like this: `std::thread t{[&comPointer] { CoInitializeEx(nullptr, COINIT_MULTITHREADED); CoCreateInstance(/* Initialize comPointer */); }}; t.join();` This is working fine so far and allows clients to use my objects in any thread they like. Not sure if there are any drawbacks? – Robert Jan 14 '16 at 16:19
  • This passes MTA COM pointer to another thread. If this new thread is not MTA, then the drawback is simple - violation of COM rules and possible unwanted behavior (failures, missing events etc). – Roman R. Jan 17 '16 at 19:20

0 Answers0