0
$\begingroup$

Rosanswers logo

Hello,

I have a custom cpp class that works well outside of ROS. Now, I would like to use one of the methods in this class as the callback function for a ros::Subscriber. However, to leave the class untouched and the method generic, I'll need some type conversion from the topic's message type to the method's argument type. Say, from std_msgs::String::ConstPtr to std::string.

Is it possible to do this implicitly during the subscriber declaration? If so, how?

Thanks in advance for any help.


Originally posted by vbs on ROS Answers with karma: 62 on 2018-04-26

Post score: 0


Original comments

Comment by PeteBlackerThe3rd on 2018-04-27:
robotchicken is right. The way to do this is with a wrapper function or class. This is a limitation of the C++ language itself and not ROS.

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

From a quick glance at the ROS API, I don't think there is a way to do it implicitly. I guess its more of a C++ function redefinition functionaility than a ROS functionaility.

You could create a class that inherits from the class outside ROS.

class ClassInsideROS: public ClassOutsideROS {
public:
    ClassInsideROS{
      // Parent Constructor goes here
      }
 
    void new_callback(std_msgs::String::ConstPtr msg)  {
        std::string msg_string;
        // Perform Type Conversion from std_msgs::String::ConstPtr to
        old_callback(msg_string)
     }
};

 void main() {
   // Register Callback
   ros::NodeHandle n;
   ClassInsideROSobj;
   ros::Subscriber sub = n.subscribe(topic, 1000, &ClassInsideROS::new_callback, &obj);
}

But if all you need is the member function and no other properties of the class, you could just create a function.

ClassOutsideROS obj_;

void new_callback(std_msgs::String::ConstPtr msg)  {  
   std::string msg_string;
   // Perform Type Conversion from std_msgs::String::ConstPtr to
   obj_.callback(msg_string) 
}

void main() {
  // Register Callback
   ros::NodeHandle n;
   InsideROS obj;
   ros::Subscriber sub = n.subscribe(topic, 1000, &ClassOutsideROS::new_callback, &obj);
}

Originally posted by robotchicken with karma: 51 on 2018-04-26

This answer was ACCEPTED on the original site

Post score: 1


Original comments

Comment by vbs on 2018-04-27:
Thank you for your reply. Indeed, that is the same solution I thought of. I was just wondering if really there wasn't any way of doing it implicitly, like using a binding function or something in the subscriber declaration. But I guess that even if there was, it would be less efficient.

$\endgroup$

Your Answer

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