2

I need to call some COM APIs from a simple REST server using the REST SDK. It's similar to the BlackJack sample code.

Whenever I try to create a COM object I get an exception that CoInitialize has not been called. But where exactly can I initialize the thread that processes the REST request? I couldn't find any documentation.

I tried the constructor (BlackJackDealer in the sample) but that does not work:

BlackJackDealer::BlackJackDealer(utility::string_t url) : m_listener(url)
{
  CoInitialize(0);
  ...
}
laktak
  • 57,064
  • 17
  • 134
  • 164

1 Answers1

1

Tasks in the C++ REST SDK execute on the Windows Threadpool by default. Instead of trying to join threadpool threads to an STA (which should be considered an anti-pattern), you can either:

  • Specify a custom scheduler (deriving from pplx::scheduler_interface) when creating tasks that need to call COM methods. See pplxinterface.h for the interface declaration and windows_scheduler::schedule() inside pplxwin.cpp for how the default scheduler is implemented on various Windows flavors.
  • Manually marshall any COM interactions to a thread that you own and control (and have called CoInitialize on). This probably means something like having a global vector of std::function objects that you protect with the usual mutex/condition_variable dance.

You may need to perform manual marshalling even if you go the custom scheduler route, but the custom scheduler will interoperate better with the existing task-based APIs.

roschuma
  • 536
  • 4
  • 7