ROS编程过程中遇到不少需要给回调函数传递多个参数的情况,下面总结一下,传参的方法:
一、回调函数仅含单个参数
1void chatterCallback(const std_msgs::String::ConstPtr& msg) 2{ 3 ROS_INFO("I heard: [%s]", msg->data.c_str()); 4} 5int main(int argc, char** argv) 6{ 7 .... 8 ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback); 9 .... 10} 11 12 13#python代码,简要示例 14def callback(data): 15 rospy.loginfo("I heard %s",data.data) 16 17def listener(): 18 rospy.init_node('node_name') 19 rospy.Subscriber("chatter", String, callback) 20 # spin() simply keeps python from exiting until this node is stopped 21 rospy.spin()
##二、回调函数含有多个参数
1#C++代码 2void chatterCallback(const std_msgs::String::ConstPtr& msg,type1 arg1, type2 arg2,...,typen argN) 3{ 4 ROS_INFO("I heard: [%s]", msg->data.c_str()); 5} 6int main(int argc, char** argv) 7{ 8 ros::Subscriber sub = 9 n.subscribe("chatter", 1000, boost::bind(&chatterCallback,_1,arg1,arg2,...,argN); 10 ///需要注意的是,此处 _1 是占位符, 表示了const std_msgs::String::ConstPtr& msg。 11} 12 13 14#python代码,python中使用字典 15def callback(data, args): 16 dict_1 = args[0] 17 dict_2 = args[1] 18... 19 20sub = rospy.Subscriber("text", String, callback, (dict_1, dict_2))
三、boost::bind()
boost::bind支持所有的function object, function, function pointer以及member function pointers,能够将行数形参数绑定为特定值或者调用所需要的参数,并可以将绑定的参数分配给任意形参。
1.boost::bind()的使用方法(functions and function pointers)
定义如下函数:
1int f(int a, int b) 2{ 3 return a + b; 4} 5 6int g(int a, int b, int c) 7{ 8 return a + b + c; 9}
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)参数列表的第一个参数。
boost::bind可以处理多个参数:
1bind(f, _2, _1)(x, y); // f(y, x) 2 3bind(g, _1, 9, _1)(x); // g(x, 9, x) 4 5bind(g, _3, _3, _3)(x, y, z); // g(z, z, z) 6 7bind(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.