Re: Casting function pointers



KKL wrote:

I wonder how casting with function pointers work, how it "should be"
handled and how it "should not be" handled.

That's actually quite simply: it "should not" be handled at all.

Whenever you think you should cast a function pointer, the probability is very high that you're trying to do the wrong thing, so it's generally best to not do it at all.

The only safe casts involving function pointers are those to other function pointer types --- and that only if you cast back to the original type before actually using the pointer to call the function. But if you must eventually go back to the original type anyway, what would be the point of casting in the first place?

Module: Task Service Abstraction Layer
int taskCreate(char* taskName, void* funcPtr, int
taskPriority,..........)
{
//Casting void* funcPtr to function pointer that returns void and
accepts no arguments
TaskProperties.entryPtr = (void ()(void)* ) funcPtr;

This is an invitation for disaster. Function pointers and data pointers don't mix. Not even if the data pointers are (void *).

And on top of that, your function pointer cast looks syntactically wrong. It should be (void (*)(void)).
.



Relevant Pages

  • Casting pointers to functions of different types
    ... It has to cast a function pointer to some ... Code which stored function pointer in array of unsigned ... typedef void; ... void marshal (AFunc func, int *args) ...
    (comp.lang.c)
  • Re: Function Pointers
    ... Just a heads-up - you don't need the cast. ... lossless conversion between void * and function pointers, ... I thought you couldn't have a generic function pointer like the 'void ... there is no generic function pointer type. ...
    (comp.lang.c)
  • Re: Plugins as game data
    ... Once you have the address of the function, cast it using a function ... // cast your void * address into the right function pointer ... somefunction(fmt, vp); ...
    (rec.games.roguelike.development)
  • Re: Plugins as game data
    ... Once you have the address of the function, cast it using a function ... // cast your void * address into the right function pointer ... Assuming that all data types involved in the function call are ...-friendly, ...
    (rec.games.roguelike.development)
  • Re: bug in visual studio .net 2003 - breakpoints and memcpy
    ... > from a function pointer to void*, ... > listed among the possible conversions. ... Otherwise the conversion is an error and the "double cast" doesn't ...
    (microsoft.public.win32.programmer.kernel)