Ask Your Question

Generic Subscriber in ROS2

asked 2020-08-17 05:38:26 -0500

nyxaria gravatar image

I am looking to replicate ROS1 behaviour where I could use ShapeShifter to subscribe to any topic, and not have to specify the message type. This code would run in C++.

I have found this Pull Request but it seems nothing has yet come of this.

Does anyone know if this is possible in ROS2 using C++? If not C++, then Python?

Many thanks

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted

answered 2020-08-17 08:16:31 -0500

updated 2020-08-17 08:24:15 -0500

Not completely what are looking for, but here is one way to do in Python. In Python, you can use get_msg_class from ros2topic.api to get the message type and then subscribe to the topic. Here is an example:

import rclpy
from rclpy.node import Node
from ros2topic.api import get_msg_class

class TestSubscriber(Node):
    def __init__(self):
        message_type = get_msg_class(self, '/topic_name', include_hidden_topics=True)
        print('Message type:', message_type)
        self.create_subscription(message_type, '/topic_name', self.on_message_received, 1)

    def on_message_received(self, message):

def main(args=None):
    test_subscriber = TestSubscriber()

if __name__ == '__main__':

Test it by running e.g.:

ros2 topic pub /topic_name std_msgs/String '{ data: test_value }'
edit flag offensive delete link more


This is awesome, thanks! Such as a shame the C++ api is not there yet.

nyxaria gravatar image nyxaria  ( 2020-08-17 08:22:39 -0500 )edit

answered 2020-08-17 07:25:57 -0500

dawonn_haval gravatar image

Take a look at rosbag2, it subscribes to serialized topics regardless of message type.

edit flag offensive delete link more


Thank you!

nyxaria gravatar image nyxaria  ( 2020-08-17 08:22:47 -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: 2020-08-17 05:38:26 -0500

Seen: 87 times

Last updated: Aug 17