ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
5

Get Const::PTR from message

asked 2014-11-04 09:10:15 -0600

Ruud gravatar image

Hi all,

For a specific function that is not a callback, I require a const sensor_msgs::ImageConstPtr& image_pointer to work with that is derived from a regular sensor_msgs::Image source_image that I already have.

How would one get such a constant image pointer from a regular message?

Thanks! Ruud

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
5

answered 2014-11-04 09:34:06 -0600

Wolf gravatar image

If its no problem for your that the data is copied you can do something like:

sensor_msgs::ImageConstPtr your_const_pointer( new sensor_msgs::Image( source_image ) );

Note that, this calls the copy constructor of sensor_msgs::Image thereby copying the underlying data. (But I guess its Ok for you because you want ConstPtr)

If you need a shared pointer that can modify the data in your original object this is not possible in this way because you cannot (safely) create a shared_pointer for a object you do not have the ownership for ( Unless you already have a shared_pointer (, which you don't,) and the object you intend to point to does not implement boost enable_shared_from_this<y> (which message types do not) ) ....

edit flag offensive delete link more

Comments

Thanks! That worked.

Ruud gravatar image Ruud  ( 2014-11-04 09:48:30 -0600 )edit
3

answered 2014-11-04 09:35:42 -0600

paulbovbel gravatar image

updated 2014-11-04 09:38:58 -0600

For reference, ImagePtr and ImageConstPtr are defined as:

typedef boost::shared_ptr< ::sensor_msgs::Image> ImagePtr;
typedef boost::shared_ptr< ::sensor_msgs::Image const> ImageConstPtr;

The quickest legal solution would be to create an ImageConstPtr with a null deleter, so that when the shared_ptr is destructed, it doesn't try to deallocate the memory. You would also have to be careful that the shared_ptr doesn't outlive your source_image object.

ImageConstPtr image_pointer(*source_image, boost::null_deleter());

However, this is not by any means the 'right way'. The best thing to do would be to initialize your source_image object as an ImagePtr in the first place, and simply pass it to the function expecting an ImageConstPtr.

edit flag offensive delete link more

Comments

Or use Wolf's suggestion to copy the data :)

paulbovbel gravatar image paulbovbel  ( 2014-11-04 09:40:51 -0600 )edit

This is a great trick when you are willing to trade a bit of safety/readability for performance.

xkortex gravatar image xkortex  ( 2021-01-31 23:17:00 -0600 )edit

Question Tools

2 followers

Stats

Asked: 2014-11-04 09:10:15 -0600

Seen: 7,779 times

Last updated: Nov 04 '14