Returning a variables form a callback function C++
Hi everyone,
I'm developing a TCP communication ROS node and I want to send a string to another ROS node. In this case, I'm using a std_msgs::String
message to send information between this two nodes. The point is that when you do ROS Tutorial, Callback function uses a global variable in order to save the std_msgs::String
value. I don't want to use a global variable because is not recomended while programming. Is there a way to use a pointer to a std::string
or anything to get that value returned without using a global variable? It would be cool if there's a way without using a class like in this example 1, because I don't want to implement a whole class just to get a string value.
Here I leave that part of my ROS code:
void tcp_listener_Callback(const std_msgs::String::ConstPtr &tcp_msgs, std::string listener_return){
listener_return = tcp_msgs->data.c_str();
}
and the ros subscriber callback:
ros::Subscriber tcp_listener_sub = nh.subscribe<std_msgs::String>("PLC_command_cmd",1000,boost::bind(tcp_listener_Callback,_1,sTCP_listener_cmd));
There is no problem with using a global variable. If you are concerned about memory you can simply use a pointer as a global variable and clear the value. Otherwise the initialization of your subscriber
tcp_listener_sub
should be done once only (not in a loop!). So this means that the return string argsTCP_listener_cmd
can be used only once in this case which beats the purpose of the subscriber.Thanks, I know that there's no problem in using a global variable. But I don't like much programming using global vars. So I just wondering if there's a method to use another pointer to a string variable to use when you call your callback function and how to do it without declaring a whole class. But I've read on the internet that using a class is the best way to achieved this, so I think I'll try it.