mardi 8 mars 2016

the best pattern to register many function callback handler in C?

I am writing a module for AT command parser, and in the AT_Parser struct, I have a list of callback that i would like to make.

When creating the AT_Parser instance, I need to register all the function callback handler in my at_parser_create method by passing as function parameter.

The example is shown below:

// at_parser.h

typedef void (*At_Handler)(uint8_t *src);

typedef struct {
  At_Handler echo;
  At_Handler data;
  At_Handler device_profile;
  At_Handler parameter_setting;
  At_Handler error;
} AT_Parser;

AT_Parser *at_parser_create(At_Handler *echo, At_Handler *data, At_Handler *device_profile, At_Handler *parameter_setting, At_Handler *error);

// at_parser.c

AT_Parser *at_parser_create(At_Handler *echo, At_Handler *data, At_Handler *device_profile, At_Handler *parameter_setting, At_Handler *error) 
{
  AT_Parser *instance = malloc(sizeof(*instance));
  instance->echo = echo;
  instance->echo = data;
  instance->echo = device_profile;  
  instance->echo = parameter_setting;  
  instance->echo = error;

  return instance;
}

// main.c

static void at_handler_echo(uint8_t *src) {}
static void at_handler_data(uint8_t *src) {}
static void at_handler_device_profile(uint8_t *src) {}
static void at_handler_parameter_setting(uint8_t *src) {}
static void at_handler_error(uint8_t *src) {}

int main(void)
{
  AT_Parser *at_parser = at_parser_create(at_handler_echo, at_handler_data, at_handler_device_profile, at_handler_parameter_setting, at_handler_error);
}

You could see from the example above, this solution does not scale, if I would have more function callback in my AT_Parser struct, I would need to have more parameters in my at_parser_create method.

Is there any better design patter or solution to solve this problem?

Aucun commentaire:

Enregistrer un commentaire