I am trying to register a custom class factory with CoRegisterClassObject, and the factory needs to be able to handle both STA and MTA objects. I'm noticing that IClassFactory::CreateInstance uses whatever threading model is specified for the current thread by CoInitializeEx. Is there a way to create the object in a different apartment and somehow marshal it back to the current apartment? For example,
CoInitializeEx(NULL, COINIT_MULTITHREADED);
CustomClassFactory *factory = new CustomClassFactory();
DWORD regNum = 0;
CLSID clsid = __uuidof(TestComObjLib::TestComObjCoClass);
CoRegisterClassObject(clsid, factory, CLSCTX_INPROC_SERVER, REGCLS_MULTIPLEUSE, ®Num);
{
TestComObjLib::ITestComObjPtr ptr;
HRESULT hr = ptr.CreateInstance(clsid, NULL);
if(ptr){
auto str = ptr->HelloWorld();
cout << str << endl;
}
}
CoRevokeClassObject(regNum);
CoUninitialize();
If TestComObjCoClass needs to be single threaded, I want to be able to do something in CustomClassFactory::CreateInstance that can create the object in a STA and marshal it to the current thread, which is in the MTA.