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

rosbag::MessageInstance derefenced pointer error

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

matthewlefort gravatar image

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

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. http://wiki.ros.org/rosbag/Code%20API

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
std_msgs/Int8
robot_mode_p: data: 24

Dereferenced robot_mode: 24

But my code outputs:

/robot_mode
std_msgs/Int8
robot_mode_p: data: 24

Dereferenced robot_mode: 

Any help is much appreciated. Thanks!

drive folder for bag file and sample code if interested: https://drive.google.com/drive/folder...

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

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

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

Comments

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: http://www.cplusplus.com/doc/tutorial... 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 -0600 )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 robot_mode_p.data (no pointer) it would still not print correctly without the cast.

EFernandes gravatar image EFernandes  ( 2019-12-12 08:58:17 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2019-12-11 18:46:28 -0600

Seen: 303 times

Last updated: Dec 12 '19