I am trying to get going with Flatbuffers in C++, but I'm already failing to write and read a struct in a union. I have reduced my original problem to an anonymous, minimal example.
Example Schema (favorite.fbs
)
// favorite.fbs
struct FavoriteNumbers
{
first: uint8;
second: uint8;
third: uint8;
}
union Favorite
{ FavoriteNumbers }
table Data
{ favorite: Favorite; }
root_type Data;
I compiled the schema using Flatbuffers 1.11.0 downloaded from the release page (I'm on Windows so to be safe I used the precompiled binaries).
flatc --cpp favorite.fbs
This generates the file favorite_generated.h
.
Example Code (fav.cpp
)
#include <iostream>
#include "favorite_generated.h"
int main(int, char**)
{
using namespace flatbuffers;
FlatBufferBuilder builder;
// prepare favorite numbers and write them to the buffer
FavoriteNumbers inFavNums(17, 42, 7);
auto inFav{builder.CreateStruct(&inFavNums)};
auto inData{CreateData(builder, Favorite_FavoriteNumbers, inFav.Union())};
builder.Finish(inData);
// output original numbers from struct used to write (just to be safe)
std::cout << "favorite numbers written: "
<< +inFavNums.first() << ", "
<< +inFavNums.second() << ", "
<< +inFavNums.third() << std::endl;
// output final buffer size
std::cout << builder.GetSize() << " B written" << std::endl;
// read from the buffer just created
auto outData{GetData(builder.GetBufferPointer())};
auto outFavNums{outData->favorite_as_FavoriteNumbers()};
// output read numbers
std::cout << "favorite numbers read: "
<< +outFavNums->first() << ", "
<< +outFavNums->second() << ", "
<< +outFavNums->third() << std::endl;
return 0;
}
I'm using unary +
to force numerical output instead of characters. An answer to another question here on StackOverflow told me I had to use CreateStruct
to achieve what I want. I compiled the code using g++ 9.1.0 (by MSYS2).
g++ -std=c++17 -Ilib/flatbuffers/include fav.cpp -o main.exe
This generates the file main.exe
.
Output
favorite numbers written: 17, 42, 7
32 B written
favorite numbers read: 189, 253, 34
Obviously this is not the desired outcome. What am I doing wrong?