I want to deserialize messages from a Bag file and publishing part of their contents with ROS for further processing.

I read a bagfile with the ROS C++ API. I know exactly the content (topic names and types) of my messages at compile time, such that I want to deserialize it into common ROS defined classes (e.g. the ones defined here https://docs.ros.org/en/noetic/api/sensor_msgs/html/index-msg.html) at runtime. Here some code:

#include <rosbag/bag.h>
#include <rosbag/view.h>
//other content
  rosbag::Bag bag;
  bag.open("foo.bag", rosbag::bagmode::Read);

  std::vector<std::string> topics{"camera1/camera_info"};

  rosbag::View view(bag, rosbag::TopicQuery(topics));

  for(auto const m : view)
      const std::string& topic_name = m.getTopic();
      std::cout << topic_name << std::endl;
      std_msgs::String::ConstPtr s = m.instantiate<std_msgs::String>();
      if (s != NULL)
          std::cout << s->data << std::endl;
      // I want the data in s as a string to be serialized into an instance
      // of the type CameraInfo located in 
      // path/ros/distro/sensor_msgs/CameraInfo.h shipping with ROS.
      CameraInfo ci = is_there_any_os_solution(s); //?


I tried to find something on this direction but I just found libraries deserializing contents unknown at compile time.

Could anyone give some hints?


1 Answer 1


I think that you're looking for the instantiate method on the rosbag MessageInstance

There's a very minimal example here

BOOST_FOREACH(rosbag::MessageInstance const m, view)
    std_msgs::Int32::ConstPtr i = m.instantiate<std_msgs::Int32>();

And more examples here and a cookbook of examples using the rosbag API.

  • $\begingroup$ Thanks! I do not know how safe this is but I tried with more complex types like CameraInfo in sensor_msgs and it really works! I thought this was only working with primitive types but how wrong I was. $\endgroup$
    – tricostume
    Commented Sep 8, 2023 at 17:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.