February 5th, 2021

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?

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_STA is not valid because it’s ambiguous: There can be multiple STA apartments in a process.

Asking for the APTTYPE_MAINSTA 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_NA will return the context for the neutral apartment. You can then use the IContext­Callback::Context­Callback method to execute code in that context.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

1 comment

Discussion is closed. Login to edit/delete existing comments.

  • Kalle Niemitalo

    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”.