Casting a function pointer to another type

后端 未结 7 1384
终归单人心
终归单人心 2020-11-22 08:07

Let\'s say I have a function that accepts a void (*)(void*) function pointer for use as a callback:

void do_stuff(void (*callback_fp)(void*), vo         


        
相关标签:
7条回答
  • 2020-11-22 08:51

    As C code compiles to instruction which do not care at all about pointer types, it's quite fine to use the code you mention. You'd run into problems when you'd run do_stuff with your callback function and pointer to something else then my_struct structure as argument.

    I hope I can make it clearer by showing what would not work:

    int my_number = 14;
    do_stuff((void (*)(void*)) &my_callback_function, &my_number);
    // my_callback_function will try to access int as struct my_struct
    // and go nuts
    

    or...

    void another_callback_function(struct my_struct* arg, int arg2) { something }
    do_stuff((void (*)(void*)) &another_callback_function, NULL);
    // another_callback_function will look for non-existing second argument
    // on the stack and go nuts
    

    Basically, you can cast pointers to whatever you like, as long as the data continue to make sense at run-time.

    0 讨论(0)
提交回复
热议问题