代码改变世界

MFC对COM的支持

2011-06-09 21:13  Clingingboy  阅读(1698)  评论(0编辑  收藏  举报

 

一.COM接口映射表

BEGIN_INTERFACE_PART(Dictionary, IDictionary)
    INIT_INTERFACE_PART(CDictionary, Dictionary)
    STDMETHOD_(BOOL, Initialize)();
    STDMETHOD_(BOOL, LoadLibrary)(LPOLESTR);
    STDMETHOD_(BOOL, InsertWord)(LPOLESTR, LPOLESTR);
    STDMETHOD_(void, DeleteWord)( LPOLESTR);
    STDMETHOD_(BOOL, LookupWord)(LPOLESTR, LPOLESTR *);
    STDMETHOD_(BOOL, RestoreLibrary)(LPOLESTR);
    STDMETHOD_(void, FreeLibrary)();
END_INTERFACE_PART_STATIC(Dictionary) 
#define BEGIN_INTERFACE_PART(localClass, baseClass) \
    class X##localClass : public baseClass \
    { \
    public: \
        STDMETHOD_(ULONG, AddRef)(); \
        STDMETHOD_(ULONG, Release)(); \
        STDMETHOD(QueryInterface)(REFIID iid, LPVOID* ppvObj); \

#ifndef _AFX_NO_NESTED_DERIVATION
#define BEGIN_INTERFACE_PART_DERIVE(localClass, baseClass) \
    class X##localClass : public baseClass \
    { \
    public: \

#else
#define BEGIN_INTERFACE_PART_DERIVE(localClass, baseClass) \
    BEGIN_INTERFACE_PART(localClass, baseClass) \

#endif
#define END_INTERFACE_PART(localClass) \
    } m_x##localClass; \
    friend class X##localClass; \

展开刚好是一个内部类,这样就省得写IUnknown的三个方法

IUnknown的实现

调用基类的三个方法就可以了

/////////////////////////////////////////////////////////////////////////////
// CDictionaryObj::XSpellCheck
STDMETHODIMP_(ULONG) CDictionaryObj::XSpellCheck::AddRef()
{
    METHOD_PROLOGUE_EX_(CDictionaryObj, SpellCheck)
    return (ULONG)pThis->ExternalAddRef();
}

STDMETHODIMP_(ULONG) CDictionaryObj::XSpellCheck::Release()
{
    METHOD_PROLOGUE_EX_(CDictionaryObj, SpellCheck)
    return (ULONG)pThis->ExternalRelease();
}

STDMETHODIMP CDictionaryObj::XSpellCheck::QueryInterface(
    REFIID iid, LPVOID* ppvObj)
{
    METHOD_PROLOGUE_EX_(CDictionaryObj, SpellCheck)
    return (HRESULT)pThis->ExternalQueryInterface(&iid, ppvObj);
}

三.引出函数

STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv)
{
    AFX_MANAGE_STATE(AfxGetStaticModuleState());
    return AfxDllGetClassObject(rclsid, riid, ppv);
}

STDAPI DllCanUnloadNow(void)
{
    AFX_MANAGE_STATE(AfxGetStaticModuleState());
    return AfxDllCanUnloadNow();
}

// by exporting DllRegisterServer, you can use regsvr.exe
STDAPI DllRegisterServer(void)
{
    AFX_MANAGE_STATE(AfxGetStaticModuleState());
    COleObjectFactory::UpdateRegistryAll();
    return S_OK;
}