【FastDDS】Layer DDS之Publisher (04-Creating a Publisher)

Fast DDS中发布者(Publisher)的创建与删除总结

一、发布者的创建(Creating a Publisher)

发布者始终属于某个域参与者(DomainParticipant),其创建通过域参与者实例的create_publisher()成员函数完成,域参与者在此过程中充当发布者的工厂。

1.1 参数说明

  • 必选参数
    用于描述发布者行为的PublisherQos。若传入PUBLISHER_QOS_DEFAULT,则使用默认发布者QoS。
  • 可选参数
    • 继承自PublisherListener的监听器(Listener),用于实现响应发布者事件和状态变化的回调函数,默认使用空回调。
    • StatusMask,用于激活或禁用PublisherListener上的各个回调触发,默认启用所有事件。

1.2 注意事项

create_publisher()在操作出错时(如提供的QoS不兼容或不被支持)会返回空指针,建议检查返回值是否为有效指针。

#include <fastdds/dds/domain/DomainParticipantFactory.hpp> #include <fastrtps/fastdds/dds/domain/DomainParticipant.hpp> #include <fastdds/dds/topic/Topic.hpp> #include <fastdds/dds/publisher/Publisher.hpp> #include <fastdds/dds/publisher/DataWriter.hpp> #include <fastdds/dds/publisher/qos/DataWriterQos.hpp> #include <fastdds/dds/core/status/StatusMask.hpp> #include <fastdds/dds/log/Log.hpp> #include <thread> #include <iostream> #include "PosPubSubTypes.h" using namespace eprosima::fastdds::dds; int main() { // 创建 DomainParticipant DomainParticipant* participant = DomainParticipantFactory::get_instance()->create_participant(0, PARTICIPANT_QOS_DEFAULT); if (!participant) { std::cerr << "创建 participant 失败" << std::endl; return 1; } // 注册类型 TypeSupport type(new topic_01::msg::PosPubSubType()); type.register_type(participant); // 创建 Topic Topic* topic = participant->create_topic("rt/pos_topic", "topic_01/msg/Pos", TOPIC_QOS_DEFAULT); if (!topic) { std::cerr << "创建 topic 失败" << std::endl; return 1; } // 创建 Publisher Publisher* publisher = participant->create_publisher(PUBLISHER_QOS_DEFAULT, nullptr); if (!publisher) { std::cerr << "创建 publisher 失败" << std::endl; return 1; } // 创建 DataWriter DataWriter* writer = publisher->create_datawriter(topic, DATAWRITER_QOS_DEFAULT, nullptr); if (!writer) { std::cerr << "创建 writer 失败" << std::endl; return 1; } // 随机数初始化 std::srand(static_cast<unsigned>(std::time(nullptr))); topic_01::msg::Pos msg; for (int i = 0; i < 100000; ++i) { for (int j = 0; j < 4; ++j) { msg.coordinates()[j] = static_cast<float>(std::rand() % 100) / 10.0f; } writer->write(&msg); std::cout << "发送消息: ["; for (int j = 0; j < 4; ++j) { std::cout << msg.coordinates()[j]; if (j != 3) std::cout << ", "; } std::cout << "]" << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } // 清理资源 participant->delete_contained_entities(); DomainParticipantFactory::get_instance()->delete_participant(participant); return 0; } 为什么这样发布的话题,ROS2的订阅者订阅不到?
07-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ray.so

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值