简体   繁体   中英

Cast a function pointer

Suppose I have a function

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

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

Is it a pointer to a function that takes a (void*) as an argument and returns a void ? Is this type of cast permitted?

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 (ie, 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.

The cast is permitted, by 5.2.10 (6):

A function pointer can be explicitly converted to a function pointer of a different type. The effect of calling a function through a pointer to a function type (8.3.5) that is not the same as the type used in the definition of the function is undefined. Except that converting a prvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are function types) and back to its original type yields the original pointer value, the result of such a pointer conversion is unspecified.

This is equivalent to C 6.3.2.3 (8):

A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer. If a converted pointer is used to call a function whose type is not compatible with the pointed-to type, the behavior is undefined.

In practice, calling through a function pointer with different but compatible argument types (especially pointer types) usually succeeds, and has the effect of a C-style cast on the arguments. This is by no means guaranteed, however; https://stackoverflow.com/a/189126/567292 discusses a case where gcc decided to make such undefined function pointer cast calls abort .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM