Casting pointers to functions of different types



Hey,

Is the following code valid? It has to cast a function pointer to some
fixed type to allow api for storing and calling that function, but is
such cast legal? Code which stored function pointer in array of unsigned
chars would be valid (I guess), but would be lot uglier than this.

typedef void (*AFunc) (void);
typedef void (*ConcreteFunc) (int);

void some_func (int)
{
}

void marshal (AFunc func, int *args)
{
ConcreteFunc cfunc = func;
cfunc (args[0]);
}

int main (void)
{
int arg = 1;
AFunc func = some_func; // here we cast ConcreteFunc to AFunc
marshal (func, &arg, 1); // and then marshal() casts it back
}

Thanks,
Yevgen
.



Relevant Pages

  • Re: int a[5] .. difference between a and &a
    ... int main{ ... Invoking undefined behaviour can give any result whatsoever. ... And what lesson will the OP draw from your apparent condoning of the cast ... void main can set your house on fire. ...
    (comp.lang.c)
  • Re: function pointer tutorial may be helpful..
    ... A function pointer is a value that is the address of a function. ... static int my_function ... void young; ...
    (comp.lang.c)
  • Re: print an address
    ... cast into (void*) and print using %p identifier rather than %u, ... even if unsigned int (the type expected for "%u" and int* happen to ... I don't think anyone has explained why the cast is ... On many implementations, different pointer types have ...
    (comp.lang.c)
  • Re: returning function pointer
    ... function pointer some_func & meanwhile calls that function and prints ... void some_func ... int main ... Note there are two parameter lists here. ...
    (comp.lang.c)
  • Re: what different between 1 and 2, why?
    ... If your compiler didn't warn you about the implicit or missing ... int main ... Again, drop the unnecessary cast. ... the standard guarantees that void* and char* ...
    (comp.lang.c)

Loading