Search code examples
c++flatbuffers

flatbuffer c++: Is it possible to steal from flatbuffers::Vector


I'm new to flatbuffer and I want to know if it's possible to get full (not const*) access to data in flatbuffers::Vector. Looking at the example below, I want to steal the ownership of img2::mem::data to store it in an Img-struct and process it in any way I want. Is this somehow possible, without memcopy-ing?

    struct Img
    {
        int iXCount;
        int iYCount;
        int iXOffset;
        unsigned char *mem;
    };

    int _tmain(int argc, _TCHAR* argv[])
    {
        Img img;
        //init img;

        flatbuffers::FlatBufferBuilder fbb;

        auto mem = fbb.CreateVector(img.mem, img.iXOffset * img.iYCount);
        auto mloc = CreateImage(fbb, img.iXCount, img.iYCount, img.iXOffset, mem);

        fbb.Finish(mloc);

        //unpack
        auto img2 = flatbuffers::GetRoot<Image>(fbb.GetBufferPointer());
        const std::uint8_t*pMem = img2->mem()->data(); //unfortunately only const*

        return 0;
    }

Solution

  • Your pMem points to data that sits somewhere in the middle of the FlatBuffer you're using. So this means you can access it, but only as long as you can keep the parent buffer around.

    Since these are bytes, you could const-cast them, and modify them in place without copying. Note that if you ever try this with things that are not bytes, you have to be aware that data in a FlatBuffer is always little-endian.

    Alternatively to const-cast, you can compile your schema with --gen-mutable, which will give you additional accessors to modify data in-place starting from GetMutableRoot, and data() will also be non-const from that.