Point a long pointer to a function?

I have the following code:

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

Long fp is a valid pointer to a function that comes in as long. I get the standard warning "make pointer from int without cast". I want to compile with:

 -std=iso9899:1990 -pedantic-errors 

which turns this warning into an error message. The question is, what is the correct translation? I tried various guesses, for example:

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

But it seems he can’t find the right one.

+4
source share
4 answers

The "correct" composition:

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

Obviously, this can be removed with a suitable typedef.

But in any case, the result of this is determined by the implementation. Avoid this if possible and keep the pointer in a pointer type. It would be intptr_t to use intptr_t if available.

+7
source

Perhaps this is something like:

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

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

 typedef void (* fnPtr)(long, char, char*); fnPtr ptr = (fnPtr) fp; 
+7
source

The only β€œright” way is not to quit at all, but rather copy the binary representation:

 long fp; void (*ptr)(long, char*, char*); memcpy(&ptr, &fp, sizeof ptr); 
+4
source

The main problem here is that ANSI-C does not allow this, despite the myriad C-APIs relying on this feature. Therefore, when compiling with -pedantic you will run into a problem. As outlined by other posters, you can spell a spell using things like memcpy() or the type of join for casting.

By the way, POSIX ensures that it works, so the part about the "results determined by the implementation" becomes much less scary.

+2
source

Source: https://habr.com/ru/post/1399652/


All Articles