《COM技术内幕》笔记(一)
//QueryInterface的实现
#include <objbase.h>
#include <unknwn.h>
#include <iostream>
using namespace std;
interface IX:IUnknown
{
virtual void __stdcall FX() = 0;
};
interface IY:IUnknown
{
virtual void __stdcall FY() = 0;
};
interface IZ:IUnknown
{
virtual void __stdcall FZ() = 0;
};
extern const IID IID_IX;
extern const IID IID_IY;
extern const IID IID_IZ;
class CA:public IX,public IY
{
virtual void __stdcall FY() {cout <<"CA::FY"<<endl; }
virtual void __stdcall FX() {cout <<"CA::FX"<<endl; }
virtual HRESULT STDMETHODCALLTYPE QueryInterface(
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject)
{
if(riid == IID_IX)
{
*ppvObject = static_cast<IX*>(this);
}
else if(riid == IID_IY)
{
*ppvObject = static_cast<IY*>(this);
}
else if(riid == IID_IUnknown)
{
*ppvObject = static_cast<IX*>(this);
}
else
{
*ppvObject = NULL;
return E_NOINTERFACE;
}
reinterpret_cast<IUnknown *>(*ppvObject)->AddRef();//引用计数加
return S_OK;
}
virtual ULONG STDMETHODCALLTYPE AddRef( void){ return 0; }
virtual ULONG STDMETHODCALLTYPE Release( void) {return 0; }
};
IUnknown * CreateInstance()
{
IUnknown * pI = static_cast <IX*>(new CA);
pI->AddRef();
return pI;
}
// {1A5EE493-AD77-4224-9A78-5F2DD3874714}
static const IID IID_IX =
{ 0x1a5ee493, 0xad77, 0x4224, { 0x9a, 0x78, 0x5f, 0x2d, 0xd3, 0x87, 0x47, 0x14 } };
// {AB55D03D-2160-4197-8AD2-36A36E33F69B}
static const IID IID_IY =
{ 0xab55d03d, 0x2160, 0x4197, { 0x8a, 0xd2, 0x36, 0xa3, 0x6e, 0x33, 0xf6, 0x9b } };
// {5443E124-25A6-451e-A634-2BA392788C38}
static const IID IID_IZ =
{ 0x5443e124, 0x25a6, 0x451e, { 0xa6, 0x34, 0x2b, 0xa3, 0x92, 0x78, 0x8c, 0x38 } };
int main(int argc, char* argv[])
{
HRESULT hr;
IUnknown *pUnknown = CreateInstance();
IX *pIX = NULL;
hr = pUnknown->QueryInterface(IID_IX,(void **)(&pIX));
if(SUCCEEDED(hr))
{
pIX->FX();
}
IY *pIY = NULL;
hr = pUnknown->QueryInterface(IID_IY,(void **)(&pIY));
if(SUCCEEDED(hr))
{
pIY->FY();
}
delete pUnknown;
system("pause");
return 0;
}
作者:洞庭散人
出处:http://phinecos.cnblogs.com/
本博客遵从Creative Commons Attribution 3.0 License,若用于非商业目的,您可以自由转载,但请保留原作者信息和文章链接URL。
posted on 2008-04-17 23:33 Phinecos(洞庭散人) 阅读(969) 评论(0) 编辑 收藏 举报