如何在运行时从平面缓冲区获取数据值和数据类型

How to get the data values and data type from flatbuffer at runtime

本文关键字:数据 获取 数据类型 缓冲区 平面 运行时      更新时间:2023-10-16

我有一个像这样定义的平面缓冲区模式

enum Payload : uint8 { BLOB, STRPARAM } //type of payload
table Header
{
payload: Payload;
sender: string;
module: string;
command: string;
parameter: string;
timestamp: string; 
status: string; // used for reply from Daemon: success or fail
message: string; // Status message, to get more info when request fails
}
table BlobPacket
{
value: [byte];
}
table StrParamPacket
{
value1: string; // e.g. "4"
value2: string; // e.g. "5.7"
}
union PacketData 
{
BlobPacket, StrParamPacket
}
table DaemonRequest
{   
header:Header; //Tells information about the packet
data:PacketData; //Actual data
}
root_type DaemonRequest;

使用以下代码打包为请求

flatbuffers::FlatBufferBuilder* _builder = nullptr;
DaemonRequestT request;
HeaderT header;
BlobPacketT blobPacket;
StrParamPacketT strParamPacket;
header.payload = 0;//str param
header.sender = sender;
header.module = module;
header.command = command;
header.parameter = parameter;
auto headerOffset = CreateHeader(*_builder, &header);
strParamPacket.value1 = value1;
strParamPacket.value2 = value2;
auto strParamPacketOffset = CreateStrParamPacket(*_builder, &strParamPacket);
auto req = CreateDaemonRequest(*_builder, &header, PacketData::StrParamPacket, strParamPacketOffset.Union());

然后将此请求发送到服务器,服务器解压缩请求 用

auto req= UnPackDaemonRequest(receivedBuffer);

通过此请求,我可以使用req->header->command等命令获取标头详细信息。 但是,我在获取联合表的data_type和数据时遇到问题。

我尝试按照平面缓冲区教程进行操作,但是没有太多文档如何在解压缩后获取数据。 生成的文件 -> "https://pastebin.com/zLEyd8BE" (使用 --gen-object-api --scoped-enums --cpp)

我尝试使用它获取数据

auto union_type = req.data_type(); //error
if (union_type == PacketData::StrParamPacket) 
{
auto strParamPacket = static_cast<const StrParamPacket*>(req->data());//error
auto command = req->header->command; //std::sting
auto parameter = req->header->parameter; //std::string
auto message = req.get()->header->message; //std::string&
auto value1 = strParamPacket.get()->value1; //std::string&
auto value2 = strParamPacket.get()->value2; //std::string&
}

这会导致以下错误

: error: ‘class std::unique_ptr<DaemonRequestT>’ has no member named ‘data_type’; did you mean ‘deleter_type’?
auto union_type = req.data_type(); //error
^~~~~~~~~
deleter_type
../Daemon/Daemon.cpp:155:76: error: no match for call to ‘(PacketDataUnion) ()’
auto strParamPacket = static_cast<const StrParamPacket*>(req->data());//error

(删除了以前的答案,因为这个问题已经澄清了)。

FlatBuffers有 2 个 API:默认的、高效的、FlatBuffers 的使用方式 API,以及一个可选的"对象 API",只有在您特殊需要时才应该使用。

您主要使用对象 API,尽管您尝试访问联合,就好像它是基本 API 一样。从错误中可以看出,req属于std::unique_ptr<DaemonRequestT>类型(不是DaemonRequest),它有一个类型PacketDataUniondata成员,而AsStrParamPacket又具有像 这样的 covenience 方法,它为您进行强制转换(如果类型错误,则返回 nullptr)。