void trace(const char* msg) { cout << msg << endl ;}
// Forward references for GUIDs
extern const IID IID_IX ;
extern const IID IID_IY ;
extern const IID IID_IZ ;
virtual void __stdcall Fx() = 0 ;
virtual void __stdcall Fy() = 0 ;
virtual void __stdcall Fz() = 0 ;
// IUnknown implementation
virtual HRESULT __stdcall QueryInterface(const IID& iid, void** ppv) ;
virtual ULONG __stdcall AddRef() ;
virtual ULONG __stdcall Release() ;
// Interface IX implementation
virtual void __stdcall Fx() { cout << "Fx" << endl ;}
// Interface IY implementation
virtual void __stdcall Fy() { cout << "Fy" << endl ;}
~CA() { trace("CA: Destroy self.") ;}
HRESULT __stdcall CA::QueryInterface(const IID& iid, void** ppv)
trace("CA QI: Return pointer to IUnknown.") ;
*ppv = static_cast<IX*>(this) ;
trace("CA QI: Return pointer to IX.") ;
*ppv = static_cast<IX*>(this) ;
trace("CA QI: Return pointer to IY.") ;
*ppv = static_cast<IY*>(this) ;
trace("CA QI: Interface not supported.") ;
reinterpret_cast<IUnknown*>(*ppv)->AddRef() ;
ULONG __stdcall CA::AddRef()
cout << "CA: AddRef = " << m_cRef+1 << '.' << endl ;
return InterlockedIncrement(&m_cRef) ;
ULONG __stdcall CA::Release()
cout << "CA: Release = " << m_cRef-1 << '.' << endl ;
if (InterlockedDecrement(&m_cRef) == 0)
IUnknown* CreateInstance()
IUnknown* pI = static_cast<IX*>(new CA) ;
// {32bb8320-b41b-11cf-a6bb-0080c7b2d682}
static const IID IID_IX =
{0x32bb8320, 0xb41b, 0x11cf,
{0xa6, 0xbb, 0x0, 0x80, 0xc7, 0xb2, 0xd6, 0x82}} ;
// {32bb8321-b41b-11cf-a6bb-0080c7b2d682}
static const IID IID_IY =
{0x32bb8321, 0xb41b, 0x11cf,
{0xa6, 0xbb, 0x0, 0x80, 0xc7, 0xb2, 0xd6, 0x82}} ;
// {32bb8322-b41b-11cf-a6bb-0080c7b2d682}
static const IID IID_IZ =
{0x32bb8322, 0xb41b, 0x11cf,
{0xa6, 0xbb, 0x0, 0x80, 0xc7, 0xb2, 0xd6, 0x82}} ;
trace("Client: Get an IUnknown pointer.") ;
IUnknown* pIUnknown = CreateInstance() ;
trace("Client: Get interface IX.") ;
hr = pIUnknown->QueryInterface(IID_IX, (void**)&pIX) ;
trace("Client: Succeeded getting IX.") ;
pIX->Fx() ; // Use interface IX.
trace("Client: Get interface IY.") ;
hr = pIUnknown->QueryInterface(IID_IY, (void**)&pIY) ;
trace("Client: Succeeded getting IY.") ;
pIY->Fy() ; // Use interface IY.
trace("Client: Ask for an unsupported interface.") ;
hr = pIUnknown->QueryInterface(IID_IZ, (void**)&pIZ) ;
trace("Client: Succeeded in getting interface IZ.") ;
trace("Client: Could not get interface IZ.") ;
trace("Client: Release IUnknown interface.") ;
本文转自Phinecos(洞庭散人)博客园博客,原文链接:http://www.cnblogs.com/phinecos/archive/2008/04/18/1159407.html,如需转载请自行联系原作者