mxs.sbrk.org ยป blog | home | projects

Cast like men in C++

Sometimes, casting void * in C++ is necessary, unfortunately, this is hard to achieve in an intuitive way and to remember the horrible syntax. Here is the problem :

#include 

int
main(int, char **)
{
  void          (*f)(void) = (void (*)(void)) dlsym(0, "SomeFunction");

  return 0;
}

Which results in the following warning:

ISO C++ forbids casting between pointer-to-function and pointer-to-object

An ugly trick to avoid this is to do it with a memcpy:

#include 
#include 

int             main(int, char **)
{
  void          (*f)(void);
  void          *ptr = dlsym(0, "SomeFunction");

  memcpy(&f, &ptr, sizeof(void *));
  return 0;
}

Generated on Sun Apr 15 13:15:41 UTC 2012 by gromit.sh