ROS回调函数传参

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.

原文链接: https://www.cnblogs.com/tiderfang/p/8968124.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    ROS回调函数传参

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/273011

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月14日 下午11:15
下一篇 2023年2月14日 下午11:17

相关推荐