libev 将参数传递给回调
libev pass argument to callback
当我们调用 ev_io_init
时,我们给它一个具有 (struct ev_loop*, struct ev_io, int)
参数的函数地址,但是我们如何使参数像 (struct ev_loop*, struct ev_io, int, void *ptr)
并使 ev_io_init
用常量调用它ptr 值?
我知道如何携带来自 struct ev_io*
的额外数据,但我猜想为每个不同的事件保存相同的数据并不是一个好方法
ASSOCIATING CUSTOM DATA WITH A WATCHER
Each watcher has, by default, a void *data
member that you can read
or modify at any time: libev will completely ignore it. This can be
used to associate arbitrary data with your watcher. If you need more
data and don't want to allocate memory separately and store a pointer
to it in that data member, you can also "subclass" the watcher type
and provide your own data:
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 since your callback will be called with a pointer to the watcher,
you can cast it back to your own type:
static void my_cb (struct ev_loop *loop, ev_io *w_, int revents)
{
struct my_io *w = (struct my_io *)w_;
...
}
More interesting and less C-conformant ways of casting your callback
function type instead have been omitted.
既然你只想传递一个指针,最简单的方法肯定是把它放在data
字段中。
当我们调用 ev_io_init
时,我们给它一个具有 (struct ev_loop*, struct ev_io, int)
参数的函数地址,但是我们如何使参数像 (struct ev_loop*, struct ev_io, int, void *ptr)
并使 ev_io_init
用常量调用它ptr 值?
我知道如何携带来自 struct ev_io*
的额外数据,但我猜想为每个不同的事件保存相同的数据并不是一个好方法
ASSOCIATING CUSTOM DATA WITH A WATCHER
Each watcher has, by default, a
void *data
member that you can read or modify at any time: libev will completely ignore it. This can be used to associate arbitrary data with your watcher. If you need more data and don't want to allocate memory separately and store a pointer to it in that data member, you can also "subclass" the watcher type and provide your own data: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 since your callback will be called with a pointer to the watcher, you can cast it back to your own type:
static void my_cb (struct ev_loop *loop, ev_io *w_, int revents) { struct my_io *w = (struct my_io *)w_; ... }
More interesting and less C-conformant ways of casting your callback function type instead have been omitted.
既然你只想传递一个指针,最简单的方法肯定是把它放在data
字段中。