开发者

Understanding a case of Callback in C

I want to understand what this code means actually, esp. the last part where the function is put into curly braces. Is the broadcast_open function somehow calling the function broadcast_recv? If yes, how?

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_cal开发者_开发百科lbacks *u)   
{ 
      abc_open(&c->c, channel, &broadcast); 
      c->u = u; 
      channel_set_attributes(channel, attributes); 
} 


It seems that broadcast_callbacks is a struct defined something like this:

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

Then the line

static const struct broadcast_callbacks broadcast_call = {broadcast_recv};

creates a new struct object whose member points to the broadcast_recv function. This member can now be used to call the broadcast_recv (which is probably part of what broadcast_open does).


You have probably seen simple variables initialized, e.g.:

int x = 4;

When it's an aggregate, such as a structure, braces are used around the initializer so the compiler knows where the initializer ends. In this case, it would appear that a function pointer is the first member of the struct.

int f(void) { return 1; }

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

Someone can now call f() with (*a_t_instance.f)(), or even a_t_instance.f()

So yes, broadcast_open or something that it calls is probably calling broadcast_receive, using the pointer in the structure.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜