ROS编程过程当中遇到很多须要给回调函数传递多个参数的状况,下面总结一下,传参的方法:html
1、回调函数仅含单个参数
void chatterCallback(const std_msgs::String::ConstPtr& msg) { ROS_INFO("I heard: [%s]", msg->data.c_str()); } int main(int argc, char** argv) { .... ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback); .... }
#python代码,简要示例 def callback(data): rospy.loginfo("I heard %s",data.data) def listener(): rospy.init_node('node_name') rospy.Subscriber("chatter", String, callback) # spin() simply keeps python from exiting until this node is stopped rospy.spin()
##2、回调函数含有多个参数node
#C++代码 void chatterCallback(const std_msgs::String::ConstPtr& msg,type1 arg1, type2 arg2,...,typen argN) { ROS_INFO("I heard: [%s]", msg->data.c_str()); } int main(int argc, char** argv) { ros::Subscriber sub = n.subscribe("chatter", 1000, boost::bind(&chatterCallback,_1,arg1,arg2,...,argN); ///须要注意的是,此处 _1 是占位符, 表示了const std_msgs::String::ConstPtr& msg。 }
#python代码,python中使用字典 def callback(data, args): dict_1 = args[0] dict_2 = args[1] ... sub = rospy.Subscriber("text", String, callback, (dict_1, dict_2))
3、boost::bind()
boost::bind支持全部的function object, function, function pointer以及member function pointers,可以将行数形参数绑定为特定值或者调用所须要的参数,并能够将绑定的参数分配给任意形参。python
1.boost::bind()的使用方法(functions and function pointers)
定义以下函数:编程
int f(int a, int b) { return a + b; } int g(int a, int b, int c) { return a + b + c; }
boost::bind(f, 1, 2)
能够产生一个无参函数对象("nullary function object"),返回f(1,2)
。相似地,bind(g,1,2,3)
至关于g(1,2,3)
。函数
bind(f,_1,5)(x)至关于
f(x,5);_1
是一个占位符,其位于f
函数形参的第一形参int a
的位置,5位于f
函数形参int b
的位置;_1
表示(x)
参数列表的第一个参数。this
boost::bind
能够处理多个参数:spa
bind(f, _2, _1)(x, y); // f(y, x) bind(g, _1, 9, _1)(x); // g(x, 9, x) bind(g, _3, _3, _3)(x, y, z); // g(z, z, z) bind(g, _1, _1, _1)(x, y, z); // g(x, x, x)
boost::bind还能够处理function object,function pointer,在此再也不细讲,能够参考https://www.boost.org/doc/libs/1_43_0/libs/bind/bind.html#Purpose.code