nnnmmm
nnnmmm

Reputation: 8754

Serializing a vector of objects with FlatBuffers

I have a vector of objects, let's call them Plumbuses, that I want to serialize with FlatBuffers. My schema for this example would be

namespace rpc;

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

table PlumbusesTable {
  plumbuses:[Plumbus];
}

root_type PlumbusesTable;

since the root type can't be a vector. Calling flatc --cpp on this file generates plumbus_generated.h with functions such as CreatePlumbusesTableDirect.

The generated GeneratePlumbusesTableDirect function expects an argument const std::vector<const Plumbus *> *plumbuses. My idea was to simply take the addresses of the objects in the vector pbs and store them in another vector, pbPtrs. Since the buffer is created and sent away before pbs goes out of scope, I thought this would not be a problem.

#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);
}

Running this, instead of 1, 2.0, 3, and 4.0, I get

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

Why does it go wrong?

Upvotes: 1

Views: 3175

Answers (1)

Aardappel
Aardappel

Reputation: 6074

This looks like this relates to a bug that was recently fixed: https://github.com/google/flatbuffers/commit/fee9afd80b6358a63b92b6991d858604da524e2b

So either work with the most recent FlatBuffers, or use the version without Direct: CreatePlumbusesTable. Then you call CreateVectorOfStructs yourself.

Upvotes: 1

Related Questions