我正在尝试执行以下插件:
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时,我将返回到A部分,但我在A部分,我不能直接调用PART B,因为它应该在回复返回时调用,那么如何在异步调用中进行循环?当我发送消息时,如何等到答复到B部分。感谢您的建议。
答案 0 :(得分: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;
}
现在,插件可以拥有任何所需的架构,也可以接收传入消息!