I want to reinterpret cast a function pointer into a void* variable. The type of the function pointer will be of type Class* (*)(void*).
Below is the sample code,
class Test
{
int a;
};
int main()
{
Test* *p(void **a);
void *f=reinterpret_cast<void*>(p);
}
The above code works well with Visual Studio/x86 compilers. But with ARM compiler, it gives compilation error. Don’t know why.
Error: #694: reinterpret_cast cannot
cast away const or other type
qualifiers
I read the explanation in Casting a function pointer to another type
I was concerned about the below explanation.
Casting between function pointers and
regular pointers (e.g. casting avoidto a
(*)(void)void*). Function
pointers aren’t necessarily the same
size as regular pointers, since on
some architectures they might contain
extra contextual information. This
will probably work ok on x86, but
remember that it’s undefined behavior.
How to do such conversions from void (*)(void*) -> void* effectively so that atleast it compiles almost the same in most of the compilers ?
reinterpret_castcan’t be used to cast a pointer to function to avoid*. While there are a few additional things that a C cast can do which aren’t allowed by combination of static, reinterpret and const casts, that conversion is not one of them.In C the cast is allowed, but it’s behavior isn’t defined (i.e. even round trip isn’t guaranteed to work).
Some POSIX functions need the conversion to be well useful.
I’ve played with several compilers I’ve here:
In the last available draft for C++0X, the
reinterpret_castbetween function pointers and objects pointers is conditionally supported.Note that if that make sense or not will depend on the target more than the compiler: a portable compiler like gcc will have a behavior imposed by the target architecture and possibly ABI.
As other have make the remark,
defines a function, not a pointer to function. But the function to pointer to function implicit conversion is made for the argument to reinterpret_cast, so what reinterpret_cast get is a
Test** (*p)(void** a).Thanks to Richard which makes me revisit the issue more in depth (for the record, I was mistaken in thinking that the pointer to function to pointer to object was one case where the C cast allowed something not authorized by C++ casts combinations).