Libev,如何参数传递给相关的回调 [英] Libev, How to pass arguments to relevant callbacks

查看:648
本文介绍了Libev,如何参数传递给相关的回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被困在参数传递libev的情况。

一般情况下,libev接收函数封装例如 * receive_callback * ,这是确定的,但在实践中,我们需要派一个相对的 * write_callback * ,以应对特定的根据接收到的包作业。例如:

  S_RECV_MSG * pstRecvMsg =(S_RECV_MSG *)recv_buff;
开关(pstRecvMsg-> wMsgType){
    情况1:
        ev_io_init(W,write_callback1,W-> FD,EV_WRITE);
        打破;
    案例2:
        ev_io_init(W,write_callback2,W-> FD,EV_WRITE);
        打破;
    案例3:
        // .......
}

我的问题是,如果 write_callbackX 还具有读取recv_buff的具体内容,我们如何能够通过recv_buff参数传递给callbackX?我们必须承担这里的全局变量的负担和丑?


解决方案

作者回答了自己,但在一个注释。由于该显示为未,我
张贴他的回答答案一节中闭循环。不知道是否有更好的方法......随时来解决这个问题。

问题作者说:


  

对不起,我想我得到了答案,现在,觉得汗颜我
  阅读文档的大意:

 结构my_io {
   ev_io IO;
   INT otherfd;
   无效* somedata;
   无论结构* mostinteresting;
};
// ...
结构my_io瓦;
ev_io_init(安培; w.io,my_cb的情况下,FD,EV_READ);


  
  

然后,我们用my_io这样​​的:

 静态无效my_cb的情况下(结构ev_loop *循环,ev_io * W_,诠释revents中)
{
   结构my_io * W =(结构my_io *)W_;
   // ...
}


I'm trapped in a situation of argument passing in libev.

Usually, libev receives packages in a function like *receive_callback*, that's OK, but in practice, we need to dispatch a relative *write_callback* to deal with specific jobs according to the received package. For example:

S_RECV_MSG* pstRecvMsg = (S_RECV_MSG*) recv_buff;
switch(pstRecvMsg->wMsgType) {
    case 1: 
        ev_io_init(w, write_callback1, w->fd, EV_WRITE);
        break;
    case 2:
        ev_io_init(w, write_callback2, w->fd, EV_WRITE);
        break;
    case 3:
        // .......
}

My question is, if the write_callbackX also has to read the specific content in the recv_buff, how can we pass the recv_buff argument to the callbackX? Must we bear the burden and ugliness of global variables here?

解决方案

The author answered it himself, but in a comment. Since this shows up as unanswered, I am posting his answer in the "answer" section and closing the loop. Not sure if there is a better way... feel free to fix this.

Question author says:

Sorry, I think I got the answer now, and feel deeply ashamed at my carelessness of reading documentation:

struct my_io{
   ev_io io;
   int otherfd;
   void *somedata;
   struct whatever *mostinteresting;
};
// ...
struct my_io w;
ev_io_init (&w.io, my_cb, fd, EV_READ);

And then we use the my_io like this:

static void my_cb (struct ev_loop *loop, ev_io *w_, int revents)
{
   struct my_io *w = (struct my_io *)w_;
   //...
}

这篇关于Libev,如何参数传递给相关的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆