代码改变世界

COM 自动化和连接点

2011-06-11 21:02  Clingingboy  阅读(630)  评论(0编辑  收藏  举报

 

一.双重接口

http://baike.baidu.com/view/1295308.htm 使用dual标记

[
    object,
    uuid(CE00527D-F8E3-46A3-8BC8-A25345AD6CAA),
    dual,
    pointer_default(unique)
]

 

二.DISPID

image

自定义DISPID,使用id标记

interface ISpeaker : IDispatch
{
    const int DISPID_VOLUME         = 1;
    const int DISPID_SPEECH         = 2;
    const int DISPID_SPEAK          = 3;

    [propget, id(DISPID_VOLUME), helpstring("property Volume")] HRESULT Volume([out, retval] LONG* pVal);
    [propput, id(DISPID_VOLUME), helpstring("property Volume")] HRESULT Volume([in] LONG newVal);
    [propget, id(DISPID_SPEECH), helpstring("property Speech")] HRESULT Speech([out, retval] BSTR* pVal);
    [propput, id(DISPID_SPEECH), helpstring("property Speech")] HRESULT Speech([in] BSTR newVal);
    [id(DISPID_SPEAK), helpstring("method Speak")] HRESULT Speak(void);
};

三.source Attribute

The [source] attribute indicates that a member of a coclass, property, or method is a source of events. For a member of a coclass, this attribute means that the member is called rather than implemented.

四.dispinterface

定义一个事件接收器(事件集合),即CallBack

dispinterface _ISpeakerEvents
{
    properties:
    methods:
    [id(DISPID_ONWHISPER), helpstring("method OnWhisper")] void OnWhisper(BSTR bstrSpeech);
    [id(DISPID_ONTALK), helpstring("method OnTalk")]    void OnTalk(BSTR bstrSpeech);
    [id(DISPID_ONYELL), helpstring("method OnYell")]    void OnYell(BSTR bstrSpeech);
};

五.c++中的事件与委托

// evh_native.cpp
#include <stdio.h>

[event_source(native)]
class CSource {
public:
    __event void MyEvent(int nValue);
};

[event_receiver(native)]
class CReceiver {
public:
    void MyHandler1(int nValue) {
        printf_s("MyHandler1 was called with value %d.\n", nValue);
    }

    void MyHandler2(int nValue) {
        printf_s("MyHandler2 was called with value %d.\n", nValue);
    }

    void hookEvent(CSource* pSource) {
        __hook(&CSource::MyEvent, pSource, &CReceiver::MyHandler1);
        __hook(&CSource::MyEvent, pSource, &CReceiver::MyHandler2);
    }

    void unhookEvent(CSource* pSource) {
        __unhook(&CSource::MyEvent, pSource, &CReceiver::MyHandler1);
        __unhook(&CSource::MyEvent, pSource, &CReceiver::MyHandler2);
    }
};

int main() {
    CSource source;
    CReceiver receiver;

    receiver.hookEvent(&source);
    __raise source.MyEvent(123);
    receiver.unhookEvent(&source);
}

关键字语法看起来很清晰,不过可惜的是不是标准c++实现

http://www.codeproject.com/KB/cpp/FastDelegate.aspx