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?
The CoÂGetÂDefaultÂContext
function will produce an IContextÂCallback
for the apartment type you specify.
APTTYPE | Result |
---|---|
CURRENT | Same as CoÂGetÂObjectÂContext |
STA | Not allowed |
MTA | Returns the multithreaded apartment |
NA | Returns the neutral apartment |
MAINSTA | Returns the main STA |
Passing 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 CoÂGetÂDefaultÂContext
with APTTYPE_
will return the context for the neutral apartment. You can then use the IContextÂCallback::
method to execute code in that context.
The documentation of the ppv parameter of CoGetDefaultContext looks like I cannot use that function if “the object’s component has not been imported into a COM+ application”.