I have a COM object implemented in a STA EXE (calls CoInitialize(NULL)
), let's call it CMyObject
which implements IControl
. Pseudo code is like this:
IControl
{
Start();
Stop();
};
CMyClass : IControl
{
public:
Start()
{
//create an ISomething in the main thread
mSomething = CoCreate(ISomething);
//this thread will make a call through ISomething
mThread = std::thread(ThreadMain, this);
}
Stop()
{
kill(mThread);
mSomething->Release();
}
UseSomething() //called from another thread
{
mSomething->DoStuff();
}
private:
std::thread mThread;
ISomething *mSomething;
};
void ThreadMain(CMyClass *o)
{
for(;;)
{
if(<some condition>)
o->UseSomething();
}
}
My test code basically follows this pattern and works without problems (so far) but reading MSDN on STA suggests I need to:
- Call
CoInitialize
/CoUninitialze
inThreadMain
- Use marshalling to call the interface from the worker thread
This question (How to access COM objects from different apartment models?) also suggests marshalling is required and advocates use of the GIT.
However apartment models is one part of COM I've never really managed to grok and I wanted to check this is necessary in my situation - especially since it is currently working nicely without errors being thrown - I don't want to add code just "in case it's needed, I can't tell".
If it makes any difference, the COM ISomething
object in question is only called by the worker thread, not by the main thread. In my specific case, only one CMyObject
will ever exist at any time.