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.
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.
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.
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?
Remove the & in front of inFavNums and it will work.
CreateStruct is a template function, which sadly in this case it means it will also take pointers without complaining about it. Would be nice to avoid that, but that isn't that easy in C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With