Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: array of void*

I'm using openCV and need some callback function. these callback function just accept limited parameters. So, if I need more variables for those function, I must make a global variables and turn it around between functions.

For example, here is the callback function :

    void mouse_callback(int event, int x, int y, int flags, void* param);
// params : addition parameter, and just one, I need more parameters for this callback.
// but cannot, so make global variable.

And because I shouldn't do that (make global variable), so I decided to make array of (void*) but I afraid C cannot make this, because size of each members can be different.

My question is : can we make array of (void*), and if not, how can I overcome my problem : use callback function and don't need to make global variable.

Thanks :)

like image 934
hqt Avatar asked Nov 22 '25 16:11

hqt


1 Answers

Define a struct that is capable of holding all necessary values and pass its address as the param argument:

struct my_type
{
    int i;
    char c;
};

void my_mouse_callback(int event, int x, int y, int flags, void* param)
{
    struct my_type* t = param;
}

Not sure what the registration mechanism is but you need to ensure that the lifetime of the object pointed to by param is valid for the calling period of the callback function:

struct my_type* mouse_param = malloc(sizeof(*mouse_param));
mouse_param->i = 4;
mouse_param->c = 'a';

register_mouse_callback(my_mouse_callback, mouse_param);

Specifically, don't do this:

{
    struct my_type mouse_param = { 4, 'a' };
    register_mouse_callback(my_mouse_callback, &mouse_param);
} /* 'mouse_param' would be a dangling pointer in the callback. */
like image 180
hmjd Avatar answered Nov 25 '25 09:11

hmjd