Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function prototype with void* parameter

I have two functions, each taking a pointer to a different type:

void processA(A *);
void processB(B *);

Is there a function pointer type that would be able to hold a pointer to either function without casting? I tried to use

typedef void(*processor_t)(void*);
processor_t Ps[] = {processA, processB};

but it didn't work (compiler complains about incompatible pointer initialization).

Edit: Another part of code would iterate through the entries of Ps, without knowing the types. This code would be passing a char* as a parameter. Like this:

Ps[i](data_pointers[j]);

Edit: Thanks everyone. In the end, I will probably use something like this:

void processA(void*);
void processB(void*);

typedef void(*processor_t)(void*);
processor_t Ps[] = {processA, processB};

...

void processA(void *arg)
{
  A *data = arg;
  ...
}
like image 249
cvoque Avatar asked Mar 22 '23 08:03

cvoque


2 Answers

If you typedef void (*processor_t)(); then this will compile in C. This is because an empty argument list leaves the number and types of arguments to a function unspecified, so this typedef just defines a type which is "pointer to function returning void, taking an unspecified number of arguments of unspecified type."

Edit: Incidentally, you don't need the ampersands in front of the function names in the initializer list. In C, a function name in that context decays to a pointer to the function.

like image 165
Andrey Mishchenko Avatar answered Mar 31 '23 15:03

Andrey Mishchenko


It works if you cast them

processor_t Ps[] = {(processor_t)processA, (processor_t)processB};

By the way, if your code is ridden with this type of things and switch's all over the place to figure out which function you need to call, you might want to take a look at object oriented programming. I personally don't like it much (especially C++...), but it does make a good job removing this kind of code with virtual inheritance.

like image 21
Guido Avatar answered Mar 31 '23 17:03

Guido