Reputation: 901
Say I have a function pointer in C- library
int (*fptr)(void);
And I have a class in c++
class A { static int func(); }
I can do following and it will be safe on any platform
ftpr = A::func;
I would like for A::func()
to return bool
.
class A { static bool func(); }
and I do not mind casting
fptr = reinterpret_cast<int(*)()>(A::func);
But will it be safe on any platform? At the first glance it seems like it will (as long as sizeof(bool) <= sizeof(int)
) but I am not so sure.
Upvotes: 0
Views: 131
Reputation: 355069
No, casting the function pointer is not safe. Calling a function via a function pointer of the wrong type yields undefined behavior.
If you need your C++ code to interoperate with C code, do not use the C++ bool
type (or, for that matter, any other C++ types that C does not have) in your interface.
Upvotes: 4