Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast a long to a function pointer?

I have the following code:

long fp = ...
void (*ptr)(long, char*, char*) = fp;

The long fp is a correct function pointer, which comes in as a long. I am getting the standard "makes pointer from int without a cast" warning. I want to be able to compile with:

-std=iso9899:1990 -pedantic-errors

which turns that warning into an error. The question is: what is the correct cast? I have tried various guesses, e.g.:

void (*ptr)(long, char*, char*) = (void)(*)(long, char*, char*) fp;

But can't seem to find the right one.

like image 495
gub Avatar asked Nov 30 '22 06:11

gub


2 Answers

The "correct" cast is:

void (*ptr)(long, char*, char*) = (void (*)(long, char*, char*))fp;

Obviously, this can be tidied up with a suitable typedef.

But either way, the result of this is implementation-defined. If you can, avoid this, and maintain the pointer in a pointer type. Next best thing would be to use intptr_t if it's available.

like image 130
Oliver Charlesworth Avatar answered Dec 15 '22 14:12

Oliver Charlesworth


Probably it's something like:

void (* ptr)(long, char, char *) = (void (*)(long, char, char *))fp;

but my suggestion is to use a typedef and forget about all this mess:

typedef void (* fnPtr)(long, char, char*);
fnPtr ptr = (fnPtr) fp;
like image 43
Matteo Italia Avatar answered Dec 15 '22 12:12

Matteo Italia