使用FlatBuffers序列化对象向量

时间:2018-01-30 11:38:05

标签: c++ flatbuffers

我有一个对象向量,让我们称之为Plumbuses,我想用FlatBuffers序列化。我这个例子的架构是

namespace rpc;

struct Plumbus
{
  dinglebopBatch:int;
  fleeb:double;
}

table PlumbusesTable {
  plumbuses:[Plumbus];
}

root_type PlumbusesTable;

因为根类型不能是向量。在此文件上调用flatc --cpp会生成plumbus_generated.h,其中包含CreatePlumbusesTableDirect等功能。

生成的GeneratePlumbusesTableDirect函数需要参数const std::vector<const Plumbus *> *plumbuses。我的想法是简单地获取向量pbs中对象的地址,并将它们存储在另一个向量pbPtrs中。由于缓冲区是在pbs超出范围之前创建并发送出去的,所以我认为这不是问题。

#include <vector>
#include <iostream>

#include "plumbus_generated.h"


void send_plumbus(std::vector<rpc::Plumbus> pbs) {
    std::vector<const rpc::Plumbus *> pbPtrs;
    pbPtrs.push_back(&(pbs[0]));
    pbPtrs.push_back(&(pbs[1]));

    flatbuffers::FlatBufferBuilder buf(1024);
    auto msg = CreatePlumbusesTableDirect(buf, &pbPtrs);
    buf.Finish(msg);

    void *msg_buf = buf.GetBufferPointer();

    // here, I'd normally send the data through a socket

    const rpc::PlumbusesTable *pbt = rpc::GetPlumbusesTable(msg_buf);
    auto *pbPtrs_ = pbt->plumbuses();
    for (const auto pbPtr_ : *pbPtrs_) {
        std::cout << "dinglebopBatch = " << pbPtr_->dinglebopBatch() << ", fleeb = " << pbPtr_->fleeb() << std::endl;
    }

}

int main(int argc, char** argv) {
    rpc::Plumbus pb1(1, 2.0);
    rpc::Plumbus pb2(3, 4.0);
    std::vector<rpc::Plumbus> pbs = { pb1, pb2 };
    send_plumbus(pbs);
}

运行它,而不是1,2.0,3和4.0,我得到了

$ ./example 
dinglebopBatch = 13466704, fleeb = 6.65344e-317
dinglebopBatch = 0, fleeb = 5.14322e-321

为什么会出错?

1 个答案:

答案 0 :(得分:1)

这看起来与最近修复的错误有关:https://github.com/google/flatbuffers/commit/fee9afd80b6358a63b92b6991d858604da524e2b

因此,要么使用最新的FlatBuffers,要么使用不带Direct的版本:CreatePlumbusesTable。然后你自己打电话给CreateVectorOfStructs