65.9K
CodeProject 正在变化。 阅读更多。
Home

易于使用的数据分发器

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.33/5 (2投票s)

2001年7月15日

1分钟阅读

viewsIcon

54074

downloadIcon

1193

一套易于使用的类,用于分发任何类型的数据。

引言

这是一个易于使用的类集合,允许将任何类型的数据分发到可能对发送者未知的对象。代码需要 RTTI 和 STL,并且依赖于模板。 如果你传递指针,你必须确保没有接收者尝试删除该指针,因为可能有多个接收者。 如果可能的话,你应该只传递可复制的对象(例如,对于引用计数对象,使用 autoptr)。 它还支持通过 threadbridge 分发到不同的线程(请参阅 关于线程 以获取有关线程的更多信息)。

这里有一个使用 MFC 的简单演示

// define your class (MFC or what ever you want)
class CMyView : public CView
{
protected: // Nur aus Serialisierung erzeugen
    CMyView();
    DECLARE_DYNCREATE(CMyView)

public:
    //
    // any function you need
    //

    // and now your data handle (for simple string)
    void HandleNewData(char* data);

protected:
    // and now the receiver
    receiver<CMyView, char*> m_MyReceiver;
};

// a channel object (my come from everywhere)
extern channel MyChannel;

// now the implementation
CMyView::CMyView()
{
    // initialize the receiver to work with your class (and function)
    m_MyReceiver.init(this, HandleNewData);

    // now link the receiver to a channel
    // object (let it be global for this example)
    // you may also place the pointer as the third parameter in init
    // you can link a receiver to any number of channels
    // you can destroy the channel or the receiver
    // at anytime (in any order!)
    m_MyReceiver.link(&MyChannel);
}

void CMyView::HandleNewData(char* data)
{
    // do what ever you want
    MessageBox(data);
}

// some where else in your application
// declare the channel object
channel MyChannel;

// and send some data
void generate_data()
{
    // send what every you want
    // every compatible receiver that's linked
    // (directly or indirectly) to this channel is called
    // NOTE: string like this are NOT const and will only work
    // with <..., char*> receivers !
    MyChannel << "Hallo Welt";
}

关于线程

也可以将一个 channel 链接到另一个 channelthreadbridge 继承自 channel,因此可以在可以使用 channel 的任何地方使用它。 请注意,threadbridge 仅在创建它的线程具有消息循环的情况下才能工作。 threadbridge::message_pump() 是一个非常简单的消息循环,可以被使用。

请注意,通过 threadbridge 发送的数据必须保持有效。 数据可能传递给多个接收者,因此你不知道数据何时不再需要。 如果你想通过指针传递数据,这可能会导致问题。 你应该使你的数据引用计数,并通过像这样的简单类传递它

template<class T>
class refptr
{
public:
    refptr(const T* v) : _V(v) {if(_V)_V->addref();}
    refptr(const refptr<T> &s) : _V(s._V) {if(_V)_V->addref();}
    ~refptr() {if(_V)_V->release();}

    operator T* () {return _V;}

    refptr<T>& operator = (const T* v) {
        if(_V)_V->release();
        _V = v;
        if(_V)_V->addref();
        return *this;
    }
protected:
    T* _V;
};

玩得开心...

许可证

本文未附加明确的许可证,但可能在文章文本或下载文件本身中包含使用条款。如有疑问,请通过下面的讨论区联系作者。

作者可能使用的许可证列表可以在此处找到。

© . All rights reserved.