Function prototype with parameter void *

I have two functions, each of which takes a pointer to a different type:

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

Is there a type of function pointer that could hold a pointer to any function without casting? I tried to use

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

but this did not work (the compiler complains about incompatible initialization of the pointer).

Edit: another part of the code will go through the Ps entries without knowing the types. This code will pass 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;
  ...
}
+4
source share
3 answers

This can be done without throws using the union:

typedef struct A A;
typedef struct B B;

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

typedef union { void (*A)(A *); void (*B)(B *); } U;

U Ps[] = { {.A = processA}, {.B = processB} };

int main(void)
{
    Ps[0].A(0); // 0 used for example; normally you would supply a pointer to an A.
    Ps[1].B(0); // 0 used for example; normally you would supply a pointer to a B.
    return 0;
}

, ; , .


-, , , char :

typedef struct A A;
typedef struct B B;

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

typedef void (*processor_t)();

void processAproxy(char *A) { processA(A); }
void processBproxy(char *B) { processB(B); }

processor_t Ps[] = { processAproxy, processBproxy };

int main(void)
{
    char *a = (char *) address of some A object;
    char *b = (char *) address of some B object;
    Ps[0](a);
    Ps[1](b);
    return 0;
}

char * , , , void *.

+1

typedef void (*processor_t)();, C. , , typedef , " return void, ."

: , . C .

+4

,

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

, switch , , , - . ( ++...), .

+1

All Articles