理解C中的回调案例

时间:2011-07-13 20:39:42

标签: c callback

我想了解这段代码的实际含义,尤其是函数放入花括号的最后一部分。 broadcast_open函数以某种方式调用函数broadcast_recv吗?如果是,怎么样?

static void broadcast_recv(struct broadcast_conn *c, const rimeaddr_t *from)
{
  printf("broadcast message received from %d.%d: '%s'\n",
         from->u8[0], from->u8[1], (char *)packetbuf_dataptr());
}

static const struct broadcast_callbacks broadcast_call = {broadcast_recv};
static struct broadcast_conn broadcast;

PROCESS_THREAD(example_broadcast_process, ev, data)
{

  broadcast_open(&broadcast, 129, &broadcast_call);

  ...

}

void broadcast_open(struct broadcast_conn *c, uint16_t channel, const struct broadcast_callbacks *u)   
{ 
      abc_open(&c->c, channel, &broadcast); 
      c->u = u; 
      channel_set_attributes(channel, attributes); 
} 

2 个答案:

答案 0 :(得分:3)

似乎broadcast_callbacks是一个结构定义如下:

struct broadcast_callbacks
{
    void (*callback)(struct broadcast_conn *, const rimeaddr_t *from);
};

然后就行了

static const struct broadcast_callbacks broadcast_call = {broadcast_recv};

创建一个新的struct对象,其成员指向broadcast_recv函数。此成员现在可用于调用broadcast_recv(这可能是broadcast_open所做的一部分。)

答案 1 :(得分:0)

您可能已经看到了初始化的简单变量,例如:

int x = 4;

如果它是一个聚合,例如结构,则在初始化程序周围使用大括号,以便编译器知道初始化程序的结束位置。在这种情况下,似乎函数指针是结构的第一个成员。

int f(void) { return 1; }

struct t {
   int (*f)(void);
   int a, b, c;
   char *d, *e, *f;
} a_t_instance = {
    f
};

有人现在可以使用f(),甚至是(*a_t_instance.f)()

来致电a_t_instance.f()

所以是的,broadcast_open或它调用的东西可能是使用结构中的指针调用broadcast_receive,