correct cast for a void *

Jul 27, 2010 at 9:34am
I was wondering what the consensus is.

I have a class blob which I pass to
a callback of void *

Is this the correct idiom to cast if I pass in a blob * ?

1
2
3
4
5
6
7
8
class blob { };

callback( void * data) 
{
    blob * b = static_cast<blob *>(data);
}


Jul 27, 2010 at 10:02am
I would think that static_cast is appropriate here; that is, casting from void* to a typed pointer.

However, I never do this, always use reinterpret_cast whenever void* is involved. I use that to mean, I want to you to treat this number in this void* thing to that type as it, without applying any conversion rules.

I think of static_cast as allowing the compiler to apply its conversions according to the language rules and reinterpet_cast as enforcing that it doesn't.
Jul 27, 2010 at 10:03am
In "C++", i would do it like this :

1
2
3
4
5
6
7
8
9
10
11
12
class callbackInterface{
...
 virtual void callback()=0;
...
};
class blob : public callbackInterface{
...
 void callback(){
  //the pointer to the blob is now 'this'
 }
 ...
};


But i'm not sure it is a good approach and useable in all cases.
In "C", i do as you wrote, with a "(type)" for the cast
Jul 27, 2010 at 11:09am
thanks chaps, so it's not bad form anyway.

bartoli, yes I was thinking along those lines.
I'm trying to knock up an interface to the C POSIX realtime
functions, timer_create etc.
but the timer callback needs to be a:

(func* )(union sigval)

so I'm not sure how i could work it in.


yet!
Jul 27, 2010 at 11:49am
You could keep that interface and let the user pass in a functor if they something more than a mere callback func.
Jul 27, 2010 at 1:16pm
boost::function and boost::bind.

www.boost.org

Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <iostream>

struct foo {
  void my_callback( int x, int y ) const
     { std::cout << __PRETTY_FUNCTION__ << " called, x = " << x << " and y = " << y << std::endl; }
}   

struct bar {
  void my_callback( int x, int y, int z ) const
     { std::cout << __PRETTY_FUNCTION__ << " called, x = " << x << " y = " << y << " and z = " << z << std::endl; }
};

int main() {
  foo f;
  bar b;

  boost::function<void( int, int )> f_callback = boost::bind( &foo::my_callback, &f, _1, _2 );
  boost::function<void( int, int )> b_callback = boost::bind( &bar::my_callback, &b, _1, _2, 42 );

  f_callback( 2, 3 );
  b_callback( 3, 4 );
}

Jul 27, 2010 at 2:10pm
thank you people.
thank you jsmith I will
take a look at that code.

I've been meaning to try the boost functional stuff.
>gulp<

Topic archived. No new replies allowed.