首页 > 解决方案 > 创建发布者 ROS2 中的分配器

问题描述

根据ROS2 文档,有第三个参数称为分配器,可以在创建发布者时使用。如何使用这个分配器?它是否为发布者分配内存?

std::shared_ptr< PublisherT > rclcpp::node::Node::create_publisher  (   const std::string &     topic_name,
const rmw_qos_profile_t &   qos_profile = rmw_qos_profile_default,
std::shared_ptr< Alloc >    allocator = nullptr 
)   

标签: c++rosros2

解决方案


自定义分配器将用于发布者上下文中的所有堆分配。这与您使用自定义分配器的方式相同,如此std::vector所示。对于 ROS2,以自定义分配器为例。

template<typename T>
struct pointer_traits {
  using reference = T &;
  using const_reference = const T &;
};

// Avoid declaring a reference to void with an empty specialization
template<>
struct pointer_traits<void> {
};

template<typename T = void>
struct MyAllocator : public pointer_traits<T> {
public:
  using value_type = T;
  using size_type = std::size_t;
  using pointer = T *;
  using const_pointer = const T *;
  using difference_type = typename std::pointer_traits<pointer>::difference_type;

  MyAllocator() noexcept;

  ~MyAllocator() noexcept;

  template<typename U>
  MyAllocator(const MyAllocator<U> &) noexcept;

  T * allocate(size_t size, const void * = 0);

  void deallocate(T * ptr, size_t size);

  template<typename U>
  struct rebind {
    typedef MyAllocator<U> other;
  };
};

template<typename T, typename U>
constexpr bool operator==(const MyAllocator<T> &,
  const MyAllocator<U> &) noexcept;

template<typename T, typename U>
constexpr bool operator!=(const MyAllocator<T> &,
  const MyAllocator<U> &) noexcept;

然后,您的主要设置看起来与没有自定义分配器的情况基本相同。

auto alloc = std::make_shared<MyAllocator<void>>();
auto publisher = node->create_publisher<std_msgs::msg::UInt32>("allocator_example", 10, alloc);
auto msg_mem_strat =
  std::make_shared<rclcpp::message_memory_strategy::MessageMemoryStrategy<std_msgs::msg::UInt32,
  MyAllocator<>>>(alloc);
std::shared_ptr<rclcpp::memory_strategy::MemoryStrategy> memory_strategy =
std::make_shared<AllocatorMemoryStrategy<MyAllocator<>>>(alloc);

对于更完整的示例,我建议查看 TLSF 分配器,该分配器旨在用于硬实时系统。它可以在这里找到,完整的例子可以在这里找到


推荐阅读