我使用ros
并尝试将订户和服务器的定义放入外部函数中。然后回调没有运行。 spin()
函数不起作用。但是我经常看到其他人将服务器的定义放到一个类中,并且回调将起作用。那么,这两个场景之间的区别是什么?
这将起作用
int main(int argc, char **argv)
{
ros::init(argc, argv, "cood_tran");
ros::NodeHandle nh;
std::cout << "coodTran" << std::endl;
target_obj = "None";
ros::param::get("target", target_obj);
ros::Subscriber ros_coord_pixel_sub =
nh.subscribe("/darknet_ros/bounding_boxes", 1, darknetCallback);
ros::Subscriber point_cloud_sub =
nh.subscribe("camera/depth_registered/points", 1, pointCouldCallback);///camera/depth_registered/points /camera/depth_registered/points<->color_optical
ros::ServiceServer location_server =
nh.advertiseService("location_srv", location);
ros::spin();
return 0;
}
这行不通
int main(int argc, char **argv)
{
ros::init(argc, argv, "cood_tran");
ros::NodeHandle nh;
coodTran(nh);
ros::spin();
return 0;
}
void coodTran(ros::NodeHandle nh)
{
std::cout << "coodTran" << std::endl;
target_obj = "None";
ros::param::get("target", target_obj);
ros::Subscriber ros_coord_pixel_sub =
nh.subscribe("/darknet_ros/bounding_boxes", 1, darknetCallback);
ros::Subscriber point_cloud_sub =
nh.subscribe("camera/depth_registered/points", 1, pointCouldCallback);///camera/depth_registered/points /camera/depth_registered/points<->color_optical
ros::ServiceServer location_server =
nh.advertiseService("location_srv", location);
}
这将起作用:
#include <darknet_ros/YoloObjectDetector.hpp>
#include <ros/ros.h>
int main(int argc, char** argv) {
ros::init(argc, argv, "darknet_ros");
ros::NodeHandle nodeHandle("~");
darknet_ros::YoloObjectDetector yoloObjectDetector(nodeHandle);
ros::spin();
return 0;
}
答案 0 :(得分:0)
在第二个片段中,您将按值传递NodeHandle。因此,在coodTran中,您正在更改原始nh的副本。 尝试像这样通过引用传递它:
void coodTran(ros::NodeHandle& nh) {
nh.sunscribe();
}
或将指针传递到原始对象:
void coodTran(ros::NodeHandle* nh) {
nh->sunscribe();
}
或在函数中创建节点并返回句柄:
ros::NodeHandle coodTran() {
ros::NodeHandle nh;
nh->sunscribe();
return nh;
}