转换函数指针 [英] Cast a function pointer
问题描述
void myFun(int *)
在C ++中, p>
(void(*)(void *))&myFun
是一个指向一个函数的指针,它以一个(void *)
并返回 void
?这种类型的演员是否被允许?
按照原样,我确定不允许。
如果删除最初的 void
周围的括号,即可得到:
void(*)(void *)
一个函数返回void并取指针void作为其唯一的参数。要转换为该类型,您需要在括号中包含整个类型的名称,因此您将得到:(void(*)(void *))
你可以按照被转换的值,得到:
(void(*)(void *))& myFun ;
至少如果内存服务,是的,这是允许的,虽然解引用指针调用它所指向的函数)通过结果可能会给出未定义的行为。特别是,当/如果你调用该函数,它期望一个指向int的指针,并将(可能)使用任何它指向为一个int。但是,如果它指向的东西没有正确对齐以用作int,它不太可能按预期工作。
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 (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.
这篇关于转换函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!