ROS入门(七) subsribe的四个参数详解
订阅节点,主要通过subscribe方式。
最常见的使用方法
void callback(const std_msgs::Empty::ConstPtr& message) { } ros::Subscriber sub = handle.subscribe("my_topic", 1, callback);
其中subscribe有很多重定义。例如:
Subscriber ros::NodeHandle::subscribe ( const std::string & topic, uint32_t queue_size, void(*)(M) fp, const TransportHints & transport_hints = TransportHints() )
Parameters:
M | [template] M here is the callback parameter type (e.g. const boost::shared_ptr<M const>& or const M&), not the message type, and should almost always be deduced |
topic | Topic to subscribe to |
queue_size | Number of incoming messages to queue up for processing (messages in excess of this queue capacity will be discarded). |
fp | Function pointer to call when a message has arrived |
transport_hints | a TransportHints structure which defines various transport-related options |
其中的参数:
topic 为订阅的节点名,字符串类型。
queue_size 为待处理信息队列大小。
fp 当消息传入时,可以调用的函数指针,即回调函数。
而其中M是回调函数的不同类型,例如const boost::shared_ptr<M const>& or const M&。这样的话,我们还可以使用boost::bind()调用回调函数。
但是,我们还会遇到subscribe()的第四个参数,例如:
Subscriber ros::NodeHandle::subscribe ( const std::string & topic, uint32_t queue_size, void(T::*)(M) fp, T * obj, const TransportHints & transport_hints = TransportHints() )
Parameters:
M | [template] M here is the message type |
topic | Topic to subscribe to |
queue_size | Number of incoming messages to queue up for processing (messages in excess of this queue capacity will be discarded). |
fp | Member function pointer to call when a message has arrived |
obj | Object to call fp on |
transport_hints | a TransportHints structure which defines various transport-related options |
当我们要使用一个Class里面的返回函数之后,我们需要调用第四个参数。例如我们有一个class:
class Listener { public: void callback(const std_msgs::String::ConstPtr& msg); };
如果想要调用这个class里的返回函数,可以使用第四个参数,如下:
Listener listener; ros::Subscriber sub = n.subscribe("chatter", 1000, &Listener::callback, &listener);
第四个参数定义的class,这样我们调用的就是Listener的callback函数。如果方法在class里面,可以使用this。如下:
class Listener { public: void callback(const std_msgs::String::ConstPtr& msg){}void TestObject(ros::NodeHandle n)
ros::Subscriber sub = n.subscribe("chatter", 1000, &Listener::callback, this);
{
}
};
这样可以调用Class里的回调函数啦。
参考资料
ROS::NodeHandle :
Using Class Methods as Callbacks:
http://wiki.ros.org/roscpp_tutorials/Tutorials/UsingClassMethodsAsCallbacks\
Using Class Methods as Callbacks issu:
https://answers.ros.org/question/207254/setting-class-method-callback-from-within-object-c/
第四个参数: