WebRTC

WebRTC信号和槽机制

2019-03-26  本文已影响39人  cx7

信号和槽的实现原理大致是这样的 :


image.png

信号对象持有连接,连接里记录了槽对象的地址和槽函数(某个成员函数)地址
信号对象发出信号,实质上是查询了连接以后 调用槽对象的槽函数并传入参数

WebRTC sigslot实现

WebRTC的信号和槽实现非常精简,代码位置(src/rtc_base/sigslot.h,src/rtc_base/sigslot.cc)
详细的代码分析可以看这个bloghttps://www.jianshu.com/p/4e5b8c1a05eb

原代码有约600行 我这里给出一个简约的实现 原理和webrtc的信号槽类似
都是保存目标对象和槽函数,参数通过模板传入.

#ifndef test_hpp
#define test_hpp

#include <stdio.h>
#include <iostream>
#include <thread>
#include <functional>

using namespace std;

//模拟槽函数
class has_slot {
    public:
    void test() {
        cout << "test : no param" << endl;
    }

    void test2(int a) {
        cout << "test2 : one param " << a << endl;
    }
    
    void test3(int a, int b) {
        cout << "test3 : two param " << a << " " << b << endl;
    }
};

class signal_base {
public:
    signal_base() {
        memset(pmethod, 0, sizeof(pmethod));
    }
    
    //连接信号和槽 拷贝成员函数到数组保存(保存的是成员函数的地址)
    template <typename T, typename... Args>
    void copy(T* p, void(T::*pm)(Args...)) {
        typedef void(T::*pm_t)(Args...);
        memcpy(pmethod, &pm, sizeof(pm_t));
    }
    
    //发送信号给槽
    template <typename... Args>
    void call(Args... args) {
        typedef void(has_slot::*pm_t)(Args...);
        
        pm_t pm;
        memcpy(&pm, pmethod, sizeof(pm_t));
        (static_cast<has_slot*>(dest)->*(pm))(args...);
    }
    
private:
    unsigned char pmethod[16];
    has_slot *dest;
};

#endif /* test_hpp */
上一篇 下一篇

猜你喜欢

热点阅读