2

Can I cast a function's pointer? This code report me an error.. Can you help me?

#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;
}
2
  • Why do you want to do that? You want some kind of hash table with functions of different signatures? Commented Jan 30, 2014 at 18:59
  • I just removed the C tag, as it doesn't make sense here. You are clearly using C++. Commented Jan 31, 2014 at 9:06

1 Answer 1

2

First, void* some_func ();, some_func is not a function pointer. You can't assign it a new value. It should be declared as function pointer as follows:

void* (*some_func) ();

or

p   some_func; 

Now just write:

some_func = (p)func;

Check working code @codepad

In C++ you do some_func = reinterpret_cast<p>(func); for c++ check this working code example @codepad

Sign up to request clarification or add additional context in comments.

4 Comments

I believe OP wanna return void * for some_func, and also C style casting is a bad choice after all.
@texasbruce I don't know C++ So i added C style only. in C++ I think it should be: ome_func = reinterpret_cast<p>(func);
AFAIK, calling a function through a pointer cast to a different type is undefined.
@molbdnilo yes (not sure for c++) but in C in this answer this is calling some_func() causes undefined behaviour. I just provided casting...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.