ros 回调函数 获取点云失败
新建一个类,订阅点云的消息。使用回调函数将订阅的点云放入一个队列中,但是发现获取点云失败。
首先,定义一个类Sub,其中的回调函数:MessageCallBack负责将订阅的点云放入队列 point_cloud_in_ptr_中
class Sub{
//主函数,订阅点云
Sub::Sub(ros::NodeHandle &nh,const std::string &topic_name,size_t buff_size){
point_sub_ = nh.subscribe(topic_name,buff_size,&subscriber::MessageCallBack,this);
}
//回调函数,将获取的点云放入point_cloud_in_ptr_中
void subscriber::MessageCallBack(const sensor_msgs::PointCloud2Ptr &point_cloud_ptr){
**point_cloud_in_ptr_**.emplace_back(point_cloud_ptr);
}
}
然后在主函数的头文件test.h中,生成一个默认的Sub对象:
test.h{
public:
......
//生成一个Sub对象
private:
Sub Subscriber_;
}
最后在主函数test.cpp中,初始化并获取点云。
TestMsg::TestMsgs(ros::NodeHandle &nh) {
........
subscriber_ = std::make_shared<Sub>(nh, "/lidar_points", 1);
........
}
结果发现,point_cloud_ptr中有点云,但是放入队列point_cloud_in_ptr_中,队列没有收到点云,打印出来后,显示这个队列的size为极大值。因此获取的点云一直是0.
经过确认,需要将写法改为以下的方法,必须使用智能指针,原因未知???
主函数的头文件test.h:
test.h{
public:
......
//生成一个Sub对象。必须使用指针std::shared_ptr
private:
std::shared_ptr<Subr> subscriber_
}
最后在主函数test.cpp中:
TestMsg::TestMsgs(ros::NodeHandle &nh) {
........
subscriber_ = std::make_shared<Sub>(nh, "/lidar_points", 1);
........
}
这样结果就正常了:
具体原因不知道,先记下来。