Events in C++

后端 未结 5 893
遇见更好的自我
遇见更好的自我 2021-01-31 10:32

I\'m not sure how to look for this online... I think they might be called something different in C++

I want to have a simple event system, somthing like

         


        
5条回答
  •  深忆病人
    2021-01-31 10:48

    There is a native Visual C++ event system. It's mostly for COM, but it has native C++ support too.

    From here:

    [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);
    }
    

提交回复
热议问题