我正在尝试使用C++中的Flatbuffers,但是我已经无法在联合中编写和读取结构。我已将最初的问题简化为一个匿名的最小示例。

示例架构(favorite.fbs)

// favorite.fbs
struct FavoriteNumbers
{
    first: uint8;
    second: uint8;
    third: uint8;
}

union Favorite
{ FavoriteNumbers }

table Data
{ favorite: Favorite; }

root_type Data;

我使用从release page下载的Flatbuffers 1.11.0编译了模式(我在Windows上,为了安全起见,我使用了预编译的二进制文件)。
flatc --cpp favorite.fbs

这将生成文件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;
}

我正在使用一元+force numerical output instead of charactersAn answer to another question here on StackOverflow告诉我我必须使用CreateStruct才能实现所需的功能。我使用M ++ 2的g++ 9.1.0编译了代码。
g++ -std=c++17 -Ilib/flatbuffers/include fav.cpp -o main.exe

这将生成文件main.exe

输出量
favorite numbers written: 17, 42, 7
32 B written
favorite numbers read: 189, 253, 34

显然,这不是理想的结果。我究竟做错了什么?

最佳答案

删除&前面的inFavNums,它将起作用。
CreateStruct是一个模板函数,在这种情况下,很遗憾,这意味着它也将使用指针而不抱怨它。避免这种情况很好,但是在C++中并不是那么容易。

10-06 07:27