I need help in function pointers.
I have two function pointer types:
typedef void (*draw_func1_t)(void* data, void* painter, double x, double y);
typedef void (*draw_func2_t)(void* data, MyPainter* painter, double x, double y);
The two types are almost the same, except the second parameter. Now I need to write a function that convert a draw_func1_t to draw_func2_t:
draw_func2_t convert_func_p(draw_func1_t func) { ... }
How can I write it? Can I just force a cast like
return (draw_func2_t)func;
because the two function prototypes are binary compatible?
Theoretically, if you cast it to a different signature and call it, it is undefined behavior, as Bathsheba's answer cites, because the calling convention for calling different types of functions can be different.
However, practically, it will work on pretty much any real-world system, because pretty much all calling conventions treat different types of (non-function) pointers identically. And since that's the only difference (everything else, including the number of parameters and return type are the same), the calling conventions will almost certainly be the same. You can check the function-calling ABI for your specific system to make sure.