ROS回调函数传参
一、回调函数仅含单个参数
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);
....
}
二、回调函数含有多个参数
#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。
}
三、boost::bind()
boost::bind支持所有的function object, function, function pointer以及member function pointers,能够将行数形参数绑定为特定值或者调用所需要的参数,并可以将绑定的参数分配给任意形参。
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)参数列表的第一个参数。
boost::bind可以处理多个参数:
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.