代码改变世界

ATL 接口映射

2011-06-21 20:16  Clingingboy  阅读(1136)  评论(0编辑  收藏  举报

 

一.BEGIN_COM_MAP && END_COM_MAP

以BEGIN和END结尾,COM_INTERFACE_ENTRY放中间

BEGIN_COM_MAP(CRandom)
    COM_INTERFACE_ENTRY(IRandom)
END_COM_MAP()

二.多重继承问题

ISphere 造成了歧义,可以用COM_INTERFACE_ENTRY_IID指定默认的实现接口

interface IGlobe : ISphere {};
interface IPlanet : ISphere {};

class CDesktopGlobe :
  public CComObjectRootEx<CDesktopGlobe>,
  public IGlobe,
  public IPlanet {
public:
  ...
BEGIN_COM_MAP(CDesktopGlobe)
  COM_INTERFACE_ENTRY(ISphere) // ambiguous
  COM_INTERFACE_ENTRY(IGlobe)
  COM_INTERFACE_ENTRY(IPlanet)
END_COM_MAP()
  // ISphere methods
  ...
  // IGlobe methods
  ...
  // IPlanet methods
  ...
};
class CDesktopGlobe :
  public CComObjectRootEx<CDesktopGlobe>,
  public IGlobe,
  public IPlanet {
public:
...
BEGIN_COM_MAP(CDesktopGlobe)
  COM_INTERFACE_ENTRY_IID(IID_ISphere, IGlobe) // unambiguous
  COM_INTERFACE_ENTRY(IGlobe)
  COM_INTERFACE_ENTRY(IPlanet)
END_COM_MAP()
...
};

三.COM_INTERFACE_ENTRY2 and COM_INTERFACE_ENTRY2_IID

具有类型转换的效果

class CDesktopGlobe :
  public CComObjectRootEx<CDesktopGlobe>,
  public IGlobe,
  public IPlanet {
public:
...
BEGIN_COM_MAP(CDesktopGlobe)
  COM_INTERFACE_ENTRY2(ISphere, IGlobe) // Use the IGlobal branch
  COM_INTERFACE_ENTRY(IGlobe)
  COM_INTERFACE_ENTRY(IPlanet)
END_COM_MAP()
...
};

四.显示接口

interface ICowboy : IUnknown {
    HRESULT Draw();
};

interface IArtist : IUnknown {
   HRESULT Draw();
};
class CAcePowell :
    public CComObjectRootEx<CComSingleThreadModel>,
    public ICowboy,
    public IArtist {
public:
BEGIN_COM_MAP(CAcePowell)
  COM_INTERFACE_ENTRY(ICowboy)
  COM_INTERFACE_ENTRY(IArtist)
END_COM_MAP()
...
  STDMETHODIMP IArtist::Draw() {
    /* Draw like an artist */
    return S_OK;
  }

  STDMETHODIMP ICowboy::Draw() {
    /* Draw like a cowboy */
    return S_OK;
  }
};

避免发生这样的问题

struct _IArtist : public IArtist {
  STDMETHODIMP Draw() { return ArtistDraw(); }
  STDMETHOD(ArtistDraw)() =0;
};

struct _ICowboy : public ICowboy {
  STDMETHODIMP Draw() { return CowboyDraw(); }
  STDMETHOD(CowboyDraw)() =0;
};

class CAcePowell :
    public CComObjectRootEx<CComSingleThreadModel>,
    public _ICowboy,
    public _IArtist {
public:
BEGIN_COM_MAP(CAcePowell)
  COM_INTERFACE_ENTRY(ICowboy)
  COM_INTERFACE_ENTRY(IArtist)
END_COM_MAP()
...
  STDMETHODIMP ArtistDraw();
  STDMETHODIMP CowboyDraw();
};

五.COM_INTERFACE_ENTRY_IMPL

缺省实现派生类