Cast a function pointer

后端 未结 2 881
孤独总比滥情好
孤独总比滥情好 2020-12-12 00:55

Suppose I have a function

void myFun(int*) 
In C++ what exactly does the following mean


  ( void(*)(void*) )&myFun

2条回答
  •  臣服心动
    2020-12-12 01:52

    As it stands, I'm pretty sure it's just not allowed.

    If you remove the parens around the initial void to get:

    void (*)(void *)
    

    ...then yes, it's a pointer to a function returning void and taking a pointer to void as its only argument. To cast to that type, you need to enclose the entire name of the type in parentheses, so you'd get: (void (*)(void *)), which you'd follow by the value being cast, to get:

    (void (*)(void *))&myFun;
    

    At least if memory serves, yes, this is allowed, though dereferencing the pointer (i.e., attempting to call the function it points at) via the result may give undefined behavior. In particular, when/if you call the function, it's expecting a pointer to int, and will (presumably) use whatever it points at as an int. If, however, what it points at isn't properly aligned to be used as an int, it's not likely to work as expected.

提交回复
热议问题