ROS:将回调函数和对象成员绑定到订阅者节点

ROS: Binding a callback function and a object member to a subscriber node

我正在写一个 class,目的是为 rviz 提供一个模型。 class 应该可以订阅一个话题来模拟一些动作。因此我想使用 node.subscribe 但问题是,subscribe 需要一个 static void 函数。这意味着我无法访问我的 class 成员和方法。

有没有可能做到这一点?

这里是缩短的代码:

MyClass.h

class MyClass
{
    private:
        tf::Transform transform;
        ros::Subscriber subscriber;

    public:
        int publish ();

    private:
        static void callback ( std_msgs::Float64MultiArray msg);
};

MyClass.cpp

MyClass::MyClass( )
{
    this->subscriber =
      this->node.subscribe( "topic_id",
                            1,
                            &MyClass::callback,
                            this->transform);
}

void MyClass::callback( std_msgs::Float64MultiArray msg, tf::Transform &transform)
{
    std::vector<double> data(4);
    data = msg.data;

    transform->setRotation( tf::Quaternion(data[0], data[1], data[2], data[3]) );
    publish ();
}

根据 ROS wiki,不需要静态空隙。 我引用此作为 here 的参考:

callback

Depending on the version of subscribe() you're using, this may be any of a few things. The most common is a class method pointer and a pointer to the instance of the class. This is explained in more detail later.

因此,只需将您的回调声明为 class 方法指针 ,而不使用静态限定符,它应该可以正常工作。

还有一点,订阅者描述中最好use boost::bind if you callback will need some arguments。 (见此 answer)。但是,这里不需要,因为您可以在 class 方法 callback.

中访问您的私有属性 transform

这是更正后的 header 代码(尽管可能很明显),添加了 node::handler 因为我真的不知道你的 node 是什么:

class MyClass
{
    private:
        ros::NodeHandle ph_;
        tf::Transform transform;
        ros::Subscriber subscriber;

    public:
        int publish ();

    private:
        void callback (const std_msgs::Float64MultiArray::ConstPtr& msg);
};

和 cpp 文件:

MyClass::MyClass( ) : ph_("~")
{
    subscriber = ph_.subscribe( "topic_id",
                            1,
                            &MyClass::callback,
                            this);
}

void MyClass::callback(const std_msgs::Float64MultiArray::ConstPtr& msg)
{
    std::vector<double> data(4);
    data = msg.data;

    transform->setRotation( tf::Quaternion(data[0], data[1], data[2], data[3]) );
    publish ();
}

干杯,