ROS回調函數傳參

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

相關文章
相關標籤/搜索