How do I get a foothold in the neutral apartment?
The neutral apartment is a mysterious beast. You cannot initialize a thread in the neutral apartment, because the neutral apartment isn’t tied to a thread. Instead, the neutral apartment takes over any thread it can find: If you are on an existing thread and call an object that lives in the neutral apartment, the calling thread is converted to a neutral apartment thread temporarily. When the call is finished, the thread is returned to its original apartment.
That’s great, but now there’s a chicken-and-egg problem: How do you get the first object into the neutral apartment?
One way is to
CoCreateInstance an object whose definition specifies that it runs in the neutral apartment. But maybe you don’t have one of those objects readily at hand. What if you just want to get into the neutral apartment directly?
CoGetDefaultContext function will produce an
IContextCallback for the apartment type you specify.
|MTA||Returns the multithreaded apartment|
|NA||Returns the neutral apartment|
|MAINSTA||Returns the main STA|
APTTYPE_ is not valid because it’s ambiguous: There can be multiple STA apartments in a process.
Asking for the
APTTYPE_ when there is no main STA will fail. And asking for anything when COM isn’t initialized will also fail.
And so we find our foothold: Calling
APTTYPE_ will return the context for the neutral apartment. You can then use the
IContextCallback:: method to execute code in that context.