Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ROS: Use lambda as callback in nodehandle.subscribe

Tags:

c++

lambda

ros

I want to be able to define a callback through a lambda but I can't get any of the function signatures to match.

std::function<void(const sensor_msgs::PointCloud2)> callback = 
 [&mycapture](const sensor_msgs::PointCloud2 msg) { 
 // do something with msg and capture
 };

auto sub = ros_node.subscribe("/sometopic", 1, callback)

I can't get this to work as subscribe wants a function pointer. Is what I'm trying to do possible with ROS? That is, can I pass into the subscribe method a lambda with a capture?

like image 271
jc211 Avatar asked Jul 27 '17 02:07

jc211


2 Answers

I have hit this issue as well in Melodic. While solution with explicit cast to boost function worked, it was very verbose. Under the hood, this solution boils to forcing compiler to choose the last overload of node_handle::subscribe that takes two template arguments:

   * \param M [template] the message type
   * \param C [template] the callback parameter type (e.g. const boost::shared_ptr<M const>& or const M&)

  template<class M, class C>
  Subscriber subscribe(const std::string& topic, uint32_t queue_size, const boost::function<void (C)>& callback

Because it is the only overload that has two template arguments, it can be enforced by specifying those parameters explicitly.

In specifics of the question asked, adding a subscriber will look like this (C++14):

ros::Subscriber subscriber = nh.subscribe<sensor_msgs::PointCloud2, const sensor_msgs::PointCloud2&>(topic, 1, [&mycapture](auto msg) {
    mycapture.workWith(msg.data);
  });
like image 121
Anton Matosov Avatar answered Sep 20 '22 16:09

Anton Matosov


I was able to get this working with capture.

T obj;
boost::function<void (const sensor_msgs::PointCloud2&)> callback = 
    [obj] (const sensor_msgs::PointCloud2& msg) {
    // Do something here 
    }
auto sub = ros_nh.subscribe<sensor_msgs::PointCloud>(topic, 1, callback);

ROS Version: Indigo
C++14

like image 30
Ross Avatar answered Sep 17 '22 16:09

Ross