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);
....
}
#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()
二、回調函數含有多個參數
#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))
三、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.
