so im working with generic stuff for example this generic function inside the struct of markov_chain:
void (*print_func)(void *);
I need to typedef it somehow
I built a generic function in my main.c file
void printfunc(void*data1)
{
char*data= (char*)data1;
printf("%s", data);
if (islast(data)==false)//if is not last we want to print " "
{
printf(" ");
}
}
now in my main: mc is pointer to markov_chain
mc->print_func=&printfunc;
then been used like this in another file, like this: markov_chain->print_func(fn->data);
the code is working great all I want is to change the function signature to the correct one
from this :
void printfunc(void*data1)
{
char*data= (char*)data1;
printf("%s", data);
if (islast(data)==false)//if is not last we want to print " "
{
printf(" ");
}
}
to this :
void (*printfunc)(void*data1)
{
char*data= (char*)data1;
printf("%s", data);
if (islast(data)==false)//if is not last we want to print " "
{
printf(" ");
}
}
I need that the code would work the same.
in my main.c, this can be changed as well if needed:
mc->print_func=&printfunc;
the calling for the function cannot be changed as it is in another file:
markov_chain->print_func(fn->data);
thank you very much. sorry for bad english.
CodePudding user response:
typedef void (*PrintFunc)(void *);
This creates a type called PrintFunc
, which is a pointer to a function with void
return and taking 1 argument of void *
. Note that I've used capitals but you can use any valid symbol, but it needs to be unique, so can't be the same as the function you are then going to implement.
void print_func(void *data) {
// do something with data...
}
You can now use the type to represent a pointer to the function (here a local variable, but in your example I suspect a member of a struct).
int main() {
PrintFunc a_printer_function = print_func;
int data = 0;
a_printer_function(&data);
return 0;
}
CodePudding user response:
The function signature you have is already correct. Your alternative doesn't make sense syntactically.
If you want to make a typedef for the function pointer type, you would do it like this:
typedef void (*print_func)(void *);
Then instead declaring a variable like this:
void (*f)(void *) = &printfunc;
You could do this:
print_func f = &printfunc;