14.3. Serialization Utilities
Fast DDS 提供了序列化 XTypes 对象的方法,从而支持高效的数据交换和在分布式系统中的操作。序列化是数据分发服务中的一个关键过程,它将复杂的数据结构转换为易于传输和重建的格式,以便能够跨不同平台和编程环境进行处理。
14.3.1. Dynamic Type to IDL
方法 idl_serialize
将一个 DynamicType
对象序列化为其 IDL 表示形式。
注意
- 转换为 IDL 仅支持以下内置注解:
@bit_bound
,@extensibility
,@key
, 和@position
。
警告
将具有继承关系的 Bitset 转换为 IDL 时,派生 Bitsets 会与其基类 Bitset 合并。
将默认值显式设置的值在 IDL 转换中会被忽略。例如,Bitmask 的默认 @bit_bound 值是 32。如果用户显式将 Bitmask 的 @bit_bound 值设置为 32,然后将 DynamicType 序列化为 IDL,则 @bit_bound 不会包含在 IDL 中。
14.3.1.1. 示例:将发现的类型转换为 IDL 格式
以下示例演示了如何使用 Fast DDS 中的 idl_serialize
方法将发现的类型转换为 IDL 格式。每当订阅者发现新的 DataReader 或 DataWriter 时,它都会使用 DynamicTypeBuilderFactory
构建一个 DynamicType,并将其序列化为 IDL 格式。有关如何实现远程类型发现的更多细节,请参考“远程类型发现与端点匹配”部分。
/* 自定义回调 on_data_reader_discovery */
void on_data_reader_discovery(
DomainParticipant* /* participant */,
eprosima::fastdds::rtps::ReaderDiscoveryStatus /* reason */,
const eprosima::fastdds::dds::SubscriptionBuiltinTopicData& info,
bool& /* should_be_ignored */) override
{
// 获取远程类型信息
xtypes::TypeObject remote_type_object;
if (RETCODE_OK != DomainParticipantFactory::get_instance()->type_object_registry().get_type_object(
info.type_information.type_information.complete().typeid_with_size().type_id(),
remote_type_object))
{
// 错误处理
return;
}
// 构建远程发现类型
DynamicType::_ref_type remote_type = DynamicTypeBuilderFactory::get_instance()->create_type_w_type_object(
remote_type_object)->build();
// 将 DynamicType 序列化为其 IDL 表示形式
std::stringstream idl;
idl_serialize(remote_type, idl);
// 打印 IDL 表示
std::cout << "发现的类型:\n" << idl.str() << std::endl;
}
/* 自定义回调 on_data_writer_discovery */
void on_data_writer_discovery(
DomainParticipant* /* participant */,
eprosima::fastdds::rtps::WriterDiscoveryStatus /*reason*/,
const eprosima::fastdds::dds::PublicationBuiltinTopicData& info,
bool& /* should_be_ignored */) override
{
// 获取远程类型信息
xtypes::TypeObject remote_type_object;
if (RETCODE_OK != DomainParticipantFactory::get_instance()->type_object_registry().get_type_object(
info.type_information.type_information.complete().typeid_with_size().type_id(),
remote_type_object))
{
// 错误处理
return;
}
// 构建远程发现类型
DynamicType::_ref_type remote_type = DynamicTypeBuilderFactory::get_instance()->create_type_w_type_object(
remote_type_object)->build();
// 将 DynamicType 序列化为其 IDL 表示形式
std::stringstream idl;
idl_serialize(remote_type, idl);
// 打印 IDL 表示
std::cout << "发现的类型:\n" << idl.str() << std::endl;
}
该代码片段展示了两个自定义回调函数:一个用于数据读取器的发现(on_data_reader_discovery
),另一个用于数据写入器的发现(on_data_writer_discovery
)。它们获取远程的数据类型信息,构建动态类型,然后将该动态类型序列化成相应的IDL表示并输出。
内容由零声教学AI助手提供,问题来源于学员提问