1

我正在尝试做一个像这样的插件:

main process()
{
   call plugin to do something;
}

plugin()
{
   PART A: to encode a message, and send to other app;
   PART B: to decode a message, and call PART A to check whether we need to send more messages.
}

因此,对于 PART B,它将在回复返回时自动调用。当我在PARTB时,我会回到PART A,但是我在PART A,我不能直接调用PART B,因为它应该在回复返回时调用,那么我如何在异步调用中进行循环?当我发送消息时,如何等待回复到达 B 部分。谢谢您的建议。

4

1 回答 1

2

这取决于您对主要流程的实现和插件的设计,例如我有这样的事情:

struct message;
typedef std::function<bool(message&)> message_handler;
struct IMainProcess {
    virtual int add_listener( message_handler const& f ) = 0;
    virtual void remove_listener( int key ) = 0;
};
struct IPlugin {
    virtual bool initialize( IMainProcess* p ) = 0;
    virtual void shutdown() = 0;
};

struct MainProcess : IMainProcess {
    int key;
    std::map<int, message_handler > listeners;
    MainProcess() : key( 0 ) {}
    virtual int add_listener( message_handler const& f ) {
        int res = key++;
        listeners[key] = f;
    }
    virtual void remove_listener( int key ) {
        listeners.erase( key );
    }

    void message_received( message& m ) {
        // call all plugins that registered for incoming messages
        for( auto i = listeners.begin(); i != listeners.end(); i++ ) {
            if( !i->second(m) ) break;
        }
    }
};
int main() {
    MainProcess mp;
    // Load plugins from some location and initialize them
    std::vector<std::auto_ptr<IPlugin> > plugins;
    while( IPlugin* p = load_plugin() ) {
        std::auto_ptr<IPlugin> sp( p );
        if( p->initialize(&mp) ) plugins.push_back( sp );
    }
    while( message* msg = wait_for_message() ) {
        std::auto_ptr<message> smsg( msg );
        mp.message_received( *msg );
    }
    // end of operation
    for( auto i = plugins.begin(); i != plugins.end(); i++ ) {
        (*i)->shutdown();
    }
    return 0;
}

现在插件可以有任何所需的架构,也可以接收传入的消息!

于 2012-10-17T10:10:57.850 回答