赞
踩
https://blog.csdn.net/xinwenfei/article/details/89384578
文中完整代码的git地址:
https://github.com/xinwf/useful/tree/master/ros/getDataOutOfCallbackWithClass/src
方法思路:借助类来实现
- #include <ros/ros.h>
- #include <std_msgs/String.h>
- #include <sstream>
-
- /**
- * This tutorial demonstrates subscribing to a topic using a class method as the callback.
- */
- // %Tag(CLASS_WITH_DECLARATION)%
- class Listener
- {
- public:
- std::string copy_data = "init init init";
- int count = 0;
- public:
- void callback(const std_msgs::String::ConstPtr& msg);
- void print_data2(){std::cout << "Copy data is :" << copy_data << "\n";}
- };
- // %EndTag(CLASS_WITH_DECLARATION)%
-
- void Listener::callback(const std_msgs::String::ConstPtr& msg)
- {
- ROS_INFO("I heard: [%s]", msg->data.c_str());
- std::stringstream ss;
- ss << msg->data.c_str();
- ss >> copy_data;
- std::cout <<"copy_data is: " << copy_data <<"\n";
- print_data2();
- ++count;
- }
-
- int main(int argc, char **argv)
- {
- ros::init(argc, argv, "listener_class");
- ros::NodeHandle n;
-
- // %Tag(SUBSCRIBER)%
- Listener listener;
- ros::Subscriber sub = n.subscribe("chatter", 1000, &Listener::callback, &listener);
- ros::Rate loop_rate(10);
- // %EndTag(SUBSCRIBER)%
- while(ros::ok() and listener.count <=3){
- ros::spinOnce();
- loop_rate.sleep();
- }
- std::cout << "After spin: \n";
- listener.print_data2();
- return 0;
- }
-
-


Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。