Skip to content

Instantly share code, notes, and snippets.

@sloretz
Last active February 20, 2023 16:47
Show Gist options
  • Save sloretz/b561a5763dc1b4e403d96e5273ce75a8 to your computer and use it in GitHub Desktop.
Save sloretz/b561a5763dc1b4e403d96e5273ce75a8 to your computer and use it in GitHub Desktop.
ROS 2 python type support and rclpy interaction

Doing import std_msgs.msg.String or from std_msgs.msg import String imports a generated Python class.

Type support

The typesupport for the String type exists on a metaclass: String.__class__._TYPE_SUPPORT. This value starts as None. It later becomes a pycapsule (with no name) when someone calls String.__class__.__import_type_support__(). This is done in rclpy by check_for_type_support(msg_type). It's called by the Node in create_...(). Afterwards inside C code the function rclpy_common_get_type_support(pymsg_type). blindly assumes _TYPE_SUPPORT is a pycapsule. The pointer from that capsule is passed to rcl_thing_init().

Deserializing

Rclpy can deserialize a ROS message to a Python instance using rclpy_deserialize(). It does this in these steps:

  1. Get the type support for the message type being deserialized
  2. Create some kind of instance of the message type.
  3. Call rmw_deserialize() to populate that message.
  4. Convert the C message type to a python type

Serializing

rclpy can serialize a Python message to bytes using rclpy_serialize(). It does so using these steps:

  1. Get the type support of the message type being serialized.
  2. Converts the Python message to a C message.
  3. Creates a serialized message object to hold the serialized data.
  4. Calls rmw_serialzie() to serialize the C message.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment