使用 Flatbuffers 读取之前写入的二进制文件的数据

Use Flatbuffers to read data of previously written binary files

我有一个二进制文件,其中包含我要加载到 Flatbuffer 对象中的数据。就像玩具示例一样,我使用以下架构:

namespace SingleInt;
table Single{
    value:uint32;
}
root_type Single;

考虑到我的二进制文件恰好包含以下信息:一个 unsigned int 值,除此之外别无其他。在这种情况下,我将值 5 存储在我的文件中。我正在尝试使用以下方法将我的二进制文件的内容分配并显示到我的 Flatbuffer 对象中:

void readFbs(){
    int fd = open("myfile", O_RDONLY, 0);
    unsigned int* memmap = (unsigned int*)mmap(0, sizeof(unsigned int), PROT_READ, MAP_SHARED, fd, 0);
    auto myfile = SingleInt::GetSingle(memmap);
    std::cout<<myfile->value()<<std::endl;
}

输出的是值 0,而不是我认为会得到的值 5

我的问题是:知道二进制文件是如何序列化和写入的,如果我创建一个表示它的模式,是否可以将其内容加载到 Flatbuffer 对象中?

编辑:写入数据的函数

void writebin(){
    unsigned int var = 5;
    std::ofstream OutFile;
    OutFile.open("myfile", std::ios::out | std::ios::binary);
    OutFile.write(reinterpret_cast<char*>(&var), sizeof(var));
    OutFile.close();
}

您的编写代码只是将裸 int 写入文件。您需要改用 FlatBuffers 函数来编写与 FlatBuffers 格式兼容的内容,例如

FlatBufferBuilder fbb;
fbb.Finish(CreateSingle(fbb, 5));
// Now write the buffer starting at fbb.GetBufferPointer() for fbb.GetSize() to a file.

更多详情请见 https://google.github.io/flatbuffers/flatbuffers_guide_tutorial.html