Ask Your Question

Convert message const ptr to non-const ptr

asked 2017-02-22 20:27:20 -0500

naikin gravatar image

What is the PROPER way to convert the ConstPtr that I receive in a message callback to a non-const ptr so that I can modify the data? What I want to do is to store a buffer of the messages my node receives and then do some additional manipulation.

I know I can manually allocate a copy the message information and store it locally, but this removes the whole point of using classes and becomes a pain when a class has member data which is another class. The autogenerated messages do not have a specific copy constructor and I could not find any good way of adding one (I don't wanna do it manually in the generated header as it will disappear if I change the message). Using the default C++ copy constructor will get me in trouble as it makes only shallow copies of complex data structures which are part of the member data of the message class and when the shared_ptr count for the message goes to 0 I will get a segfault.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2017-02-23 00:50:07 -0500

gvdhoorn gravatar image

I don't know about converting (as that would seem to violate semantics), but according to wiki/roscpp/Overview - Publishers and Subscribers - Subscribing to a Topic - Callback Signature, non-const callbacks are also fully supported:

You can also request a non-const message, in which case a copy will be made if necessary (i.e. there are multiple subscriptions to the same topic in a single node):

void callback(const boost::shared_ptr<std_msgs::String>&);
void callback(boost::shared_ptr<std_msgs::String>);
void callback(const std_msgs::StringPtr&);
void callback(const std_msgs::String::Ptr&);
void callback(std_msgs::StringPtr);
void callback(std_msgs::String::Ptr);
void callback(const ros::MessageEvent<std_msgs::String>&);
edit flag offensive delete link more


Thanks, that indeed works in some cases, but I cannot make it work with actionlib because it expects a ConstPtr.

naikin gravatar image naikin  ( 2017-02-23 04:48:30 -0500 )edit

So this is basically an xy-problem then?

gvdhoorn gravatar image gvdhoorn  ( 2017-02-24 14:13:54 -0500 )edit

Partially, yes. Sorry about that. I failed to mention it is about actionlib in particular cause I was not aware there is a difference. Again, what I really want is to end up with non-const ptr to the message when I receive it with actionlib.

naikin gravatar image naikin  ( 2017-02-24 18:16:40 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2017-02-22 20:27:20 -0500

Seen: 2,224 times

Last updated: Feb 23 '17