Call a void* as a function without declaring a function pointer

后端 未结 3 522
深忆病人
深忆病人 2021-02-05 15:32

I\'ve searched but couldn\'t find any results (my terminology may be off) so forgive me if this has been asked before.

I was wondering if there is an easy way to call a

相关标签:
3条回答
  • 2021-02-05 16:14

    I get awfully confused when casting to function types. It's easier and more readable to typedef the function pointer type:

    void *ptr = ...;
    typedef void (*void_f)(void);
    ((void_f)ptr)();
    
    0 讨论(0)
  • 2021-02-05 16:32

    In C++: reinterpret_cast< void(*)() > (ptr) ()

    The use of reinterpret_cast saves you a set of confusing parentheses, and the < > clearly sets the type apart from the call itself.

    0 讨论(0)
  • 2021-02-05 16:33

    Your cast should be:

    ((void (*)(void)) ptr)();
    

    In general, this can be made simpler by creating a typedef for the function pointer type:

    typedef void (*func_type)(void);
    ((func_type) ptr)();
    

    I should, however, point out that casting an ordinary pointer (pointer to object) to or from a function pointer is not strictly legal in standard C (although it is a common extension).

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