Ask Your Question

rosbag::MessageInstance derefenced pointer error

asked 2019-12-11 18:46:28 -0500

matthewlefort gravatar image

updated 2019-12-11 19:00:46 -0500

I am trying to follow this sample code to pull data from a bag file but am running into a bug that I cannot figure out. Hopefully this is the right forum to ask this in.

The c++ api specially "Example usage for read:" of the link below.

I successfully recreated the write/read bag file examples, but when trying to apply to my own problem I cannot access the data within the returned pointer of rosbag::MessageInstance.instantiate().

I have a bag file containing topic /robot_mode of type std_msgs::Int8 that I would like to access its data member. However the call to robot_mode_p->data returns strange items.

Sample code:

BOOST_FOREACH(rosbag::MessageInstance const m, view)
    cout << m.getTopic() << endl;
    if (m.getTopic() == mode_topic )
        std_msgs::Int8::ConstPtr robot_mode_p = m.instantiate<std_msgs::Int8>();
        std::string message_def = m.getDataType();
        cout << message_def << endl;
        cout << "robot_mode_p: " << *robot_mode_p << endl;
        if (robot_mode_p != nullptr)
            cout << "Dereferenced robot_mode: " << robot_mode_p->data << endl;


I would expect in output of:

robot_mode_p: data: 24

Dereferenced robot_mode: 24

But my code outputs:

robot_mode_p: data: 24

Dereferenced robot_mode: 

Any help is much appreciated. Thanks!

drive folder for bag file and sample code if interested:

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2019-12-12 06:14:11 -0500

EFernandes gravatar image

Wrap the value in a cast

cout << "Dereferenced robot_mode: " << static_cast<int>(robot_mode_p->data) << endl;
edit flag offensive delete link more


Wow! Thank you for the quick reply and correct answer. I will take a look at casting and pointers, would like to understand the why behind this.

For those interested: seems the static_cast is returning the pointer to its base type (int)? Please correct me if I misunderstand.

matthewlefort gravatar image matthewlefort  ( 2019-12-12 08:23:27 -0500 )edit

Glad to help! While I recommend to still look at casting and pointers, the problem it's not related to that, but cout itself. If you tried to print (no pointer) it would still not print correctly without the cast.

EFernandes gravatar image EFernandes  ( 2019-12-12 08:58:17 -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: 2019-12-11 18:46:28 -0500

Seen: 119 times

Last updated: Dec 12 '19