Unable to deserialize flatbuf messages received through TCP

0

I am trying to serialize, then deserialize a FlatBuf object.

I am using FlatBuffer 1.10.0. I want to send the serialized data through TCP to another process, but at the moment I am not able to deserialize it even in the same function.

The fbs file:

table StringPacket
{
    type:int;
    logLevel:int;
    myAge:int;

    stringdata:string;
}

root_type StringPacket;

The code in C++:

...
    uint8_t * packet_data;
    int data_size;

    using namespace flatbuffers;

    FlatBufferBuilder fbb;

    //serialize the string data
    auto thisStringData = fbb.CreateString(m_stringdata);

    //create the packet (I tried thisway too)
    //auto packet = CreateStringPacket(fbb, 2, 3, 27, thisStringData);

    StringPacketBuilder strbuilder(fbb);
    strbuilder.add_logLevel(3);
    strbuilder.add_myAge(4);
    strbuilder.add_type(1);
    strbuilder.add_stringdata(fbb.CreateString("somehing"));
    auto thisPacket = strbuilder.Finish();

    packet_data = fbb.GetBufferPointer();
    data_size = fbb.GetSize();


    auto get = GetStringPacket(packet_data);

    std::cout << "Deserialized Log level: " << get->logLevel()<<std::endl;
    std::cout << "Des Age: " << get->myAge() << std::endl;
...

I get an unhandled exception of 0xC0000005, Access violation reading location...
at the line:

std::cout << "Deserialized Log level: " << get->logLevel()<<std::endl;

Or anytime when I call a function of the 'get' object.

What am I doing wrong? How can I correctly deserialize it?

c++
flatbuffers
asked on Stack Overflow Feb 4, 2019 by istik • edited Feb 5, 2019 by istik

1 Answer

2

Please make sure you test with asserts on (in "debug" mode), as it would have answered your questions already. In particular:

  • You are calling GetBufferPointer on an unfinished buffer (which normally asserts). You need to call fbb.Finish(thisPacket) or similar.
  • You are calling CreateString inside a table builder (which normally asserts), and you create a string outside of it which you don't use. Presumably you had intended to call strbuilder.add_stringdata(thisStringData) instead.
answered on Stack Overflow Feb 4, 2019 by Aardappel

User contributions licensed under CC BY-SA 3.0