0
$\begingroup$

Rosanswers logo

Hi all, Is there any way to make one general callback in c++ that can be executed for every subscriber? I mean every callback needs type of the message but I want one callback that should be generally and dynamically executable for all subscriber. I can do this in python but need to do in c++. Has someone done this? Thanks in advance, regards, safdar


Originally posted by safzam on ROS Answers with karma: 111 on 2011-09-20

Post score: 1


Original comments

Comment by safzam on 2011-09-20:
I mean , for example I have two different nodes publishing one publishes int type message on toip1 and other publishes on topic2. Now I need to make certainly two subscriber s1 for topic1 and s2 for topic2. But I want to have one callback for both of these s1 and s2. Is it possible in C++? regards

Comment by tfoote on 2011-09-20:
Can you be a little clearer about what you mean by a generally and dynamically executable callback? The roscpp implementation is designed to take advantage of C++ types and requires you to know the type of the function to call back. Maybe your use case or what you are doing in python would help.

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

If both topics publish the same message type, you can definitely use the same callback for both subscriptions, although you won't be able to tell which message came from which topic.

Otherwise, you could always delegate the work to a third function, like this:

void processInt (int a)
{
  // Lots of computation here
}

void callback1 (MyMessageConstPtr msg)
{
  processInt (msg->int_value);
}

void callback2 (MyOtherMessageConstPtr msg)
{
  processInt (msg->other_int_value);
}

int main (int argc, char** argv)
{
  ros::init (argc, argv, "my_node");
  ros::NodeHandle node;
  ros::Subscriber s1 = node.subscribe<MyMessage>("topic1", 1, callback1);
  ros::Subscriber s2 = node.subscribe<MyOtherMessage>("topic2", 1, callback2);
  ros::spin();
  return 0;
}

Originally posted by roehling with karma: 1951 on 2011-09-21

This answer was ACCEPTED on the original site

Post score: 1


Original comments

Comment by Lorenz on 2011-09-21:
In C++ you need to know the data types when writing the program if you want to work with the data in the messages.

Comment by safzam on 2011-09-21:
Hi, I have done the same way before but it needs as many functions as we have different datatypes which I dont know in prior for example. So I want to avoid all so many functions. Is there other way?

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.