Function's pointer cast

How to cast correctly a function's pointer?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

typedef float (* MyFuncPtrType) (int, char*);
typedef void* (*p) ();

void* some_func ();

int main(int argc, char** argv)
{
	MyFuncPtrType func;
	
	some_func = reinterpret_cast<p>(func);
	
	return 0;
}
You don't. It causes undefined behavior to do so.

A simple C cast should do the trick.
Not even a simple C cast works:

 
some_func = ((p)func);
You don't. It causes undefined behavior to do so.


This.

You should not be trying to do this. It won't work.

When you call a function, the computer might have to do a lot of "behind the scenes" work to do it... such as pushing parameters to the stack, and adjusting the stack pointer, etc, etc.

If you cast that function to some incompatible type, then try to call it, the stack could be screwed up. Possibly leading to memory corruption and other "very bad things".

So yeah. What's you're trying to do is wrong. Don't do it.
It should also be noted that in this code, some_func is not a function pointer but instead an actual function declaration.
Topic archived. No new replies allowed.