代码如下:
外部组件创建后,接着创建内部组件
IUnknown* pUnknownOuter = this; // this的值为&CA
CoCreateInstance(CLSID_CB,
pUnknownOuter,
CLSCTX_INPROC_SERVER,
IID_IUnknown,
(void**)&m_pUnknownInner);
m_pUnknownInner为外部组件的成员
{
IClassFactory* pIFactory = NULL;
CoGetClassObject(CLSID_IB,
NULL,
IID_IClassFactory,
(void**)&pIFactory);
pIFactory->CreateInstace(pUnknownOuter,iid,ppv);
}
CreateInstace(IUnknown* pUnknownOuter,const IID& iid,void** ppv)
{
//只能被IID_IUnknown接口聚合
if ((pUnknownOuter != NULL) && (iid != IID_IUnknown))
{
return CLASS_E_NOAGGREGATION ;
}
CB* pB = new(pUnknownOuter);
pB->NonQueryInterface(iid,ppv);
}
CB::NonQueryInterfacer(IID& iid,void** ppv)
{
if (iid = IID_IUnknown)
*ppv = static_cast<INonUnknown*>(this);
}
实际上CB的构造函数是这样的:
CB::CB(IUnknown* pUnknownOuter) : m_cRef(1)
{
::InterlockedIncrement(&g_cComponents) ;
if (pUnknownOuter == NULL) //不使用聚合,转换成非委托接口
{
m_pUnknownOuter = reinterpret_cast<IUnknown*>
(static_cast<INondelegatingUnknown*>
(this)) ;
}
else
{ //使用聚合 转换成外部接口
m_pUnknownOuter = pUnknownOuter ;
}
}