Setting class method callback from within object (C++)
I have some object-oriented C++ code where I'm trying to create a subscriber in the constructor of the class, and that subscriber's callback function should be one of the class's functions. I have been following the relevant tutorial, but with using this
instead of a variable pointing to the class object, but am stuck with an issue. When I use the code below, it compiles properly but whenever the callback is called, it uses default values for private class variables instead of the ones that the object should have.
class TestObject
{
private:
std::string _objectName;
ros::Subscriber _testSubscriber;
public:
testCallback(const geometry_msgs::TransformStamped::ConstPtr& msg)
{
ROS_INFO("Callback made from object with name: -- %s --", _objectName.c_str());
}
TestObject(std::string objectName, ros::NodeHandle n)
{
_objectName = objectName;
_testSubscriber = n.subscribe("topicName", 1, &TestObject::testCallback, this);
}
}
static std::map<std::string, TestObject> testObjects;
int main(int argc, char **argv)
{
ros::init(argc, argv, "test_node");
ros::NodeHandle n;
TestObject newObject("objname");
testObjects["firstObject"] = newObject;
ros::spin();
return 0;
}
Now when a message is published on that topic, this node would output the following:
[INFO] [Timethingy]: Callback made from object with name: -- --
i.e. it will have an empty string, even though the string should have been set when the object was constructed.
In summary: the tutorial linked above assumes that a subsciption callback function inside a class is set from outside that class; how can I set it from inside an instance of the same class, while retaining access to all of that class instance's set variables?
Does your Object exists at the time the callback is triggered? if you already left the Object, Ros ll generate a new one.
Did u tried it with a static std::string?
This seems to be a bug in your c++ code unrelated to ROS.
Please post the calling code as well.
@ReneGaertner the object should still exist, because it exists in a global static map (see my edit to the code in the OP). @Georg, I have updated the OP to show the calling code as well.