ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange |
1 | initial version |
Callbacks with class member functions are a little tricky. "Regular" functions are merely a pointer to some code in memory. Class member functions have additional state information, namely the object instance they belong to, so you cannot just plug a member function into a regular function pointer and expect it to work.
There are two easy ways to solve this. Firstly, the ROS developers anticipated this problem and provided a neat alternative subscribe
method that accepts member functions and the corresponding object like this:
sub = n.subscribe("/camera/depth_registered/points", 1000, &Example::callBack, this);
The &Example::callBack
is the function pointer to the member function, and this
is the object instance for which you want to have the callback called.
But even if they had forgotten, the second option is to use boost::bind()
, a very powerful tool to bind arguments to arbitrary functions, which supports class member functions as well:
sub = n.subscribe("/camera/depth_registered/points", 1000, boost::bind(&Example::callBack, this, _1));
The syntax is slightly more complicated, but it is much more versatile (read the Boost documentation for details).