0

I am trying to create a structure called button ressource, that will store all the attributes of a button.

My problem is with the command function "void on select" which should be a function with unkonow number and type of parameters right now i'm using a pointer on a function that takes only one param that i've declared as one of the structure element, but i need a better way in case i need to execute a command with unkonw number and type of parameters.

struct button_ressource 
{
    unsigned char *image_off;
    unsigned char *image_on;
    unsigned int width
    unsigned int h;
    void (*on_select)(void *data);  // the button command
    int param;  // this param will be passed to the on_select command
};
typedef struct button_ressource button_res; 
MBA_BAT88
  • 55
  • 6
  • 2
    possible duplicate of [An example of use of varargs in C](http://stackoverflow.com/questions/15784729/an-example-of-use-of-varargs-in-c) – Ôrel Mar 04 '15 at 09:13
  • @Ôrel: disaggree! varargs have nothing todo with his problem. – dhein Mar 04 '15 at 09:15
  • This looks like a misguided design. `on_select` is called from outside the button. It should pass the same arguments to all buttons. Other information will come from the application. – M Oehm Mar 04 '15 at 09:16
  • i don't think that the varargs is what i'm looking for – MBA_BAT88 Mar 04 '15 at 09:32
  • For a button, you don't need any additional info:The only interesting thing is that the button was clicked and `on_select` called. For more complex GUI elements, you can pass an event struct, that holds information about mouse position or meta keys held down during clicking or the id of an item selected in a listbox, etc. – M Oehm Mar 04 '15 at 09:59

1 Answers1

3

You can't do that, in C.

You're going to have to figure out a common "protocol" for all callbacks, or use a union of a bunch of different ones (plus add information so you know which one to use) or something like that.

You can use variable arguments, but then you have to use an explicit va_list argument, you can't "pass on" the ... part directly.

In you solution, even if we assume you could express the function itself, how would you deal with the parameters? You can't replace int param; with anything param[ANY_AMOUNT];, there is no anything in C and an array can't have an infinite length either ... I'm trying to illustrate that your "dream solution" doesn't work in C.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • yes i thought of the varargs function but i don't think that's what i'm looking for cz in that case i must go through the va_list, what i need is to excute the called command as it is there'is no common way for all commands – MBA_BAT88 Mar 04 '15 at 09:42
  • well, that's what i'm trying to find out – MBA_BAT88 Mar 04 '15 at 09:58