FlatBuffers:写入和读取二进制文件? [英] FlatBuffers: Write to and read from binary file?

查看:67
本文介绍了FlatBuffers:写入和读取二进制文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C ++和Google FlatBuffers 的文件流有基本的了解.Schema文件非常简单,还创建了一个缓冲区并读取从缓冲区指针.我没有得到的是如何将多个缓冲区保存到一个二进制文件中,然后将该二进制文件读取到获取任何随机缓冲区.

I have basic knowledge of file streams in C++ and Google FlatBuffers. The Schema file is quite simple, also creating a buffer and reading from a buffer pointer. The thing that I don't get is how to save multiple buffers into a binary file, and then read that binary file to get any random buffer.

这是带有两个浮点数组的简单架构:

Here is a simple Schema with two arrays of floats:

table Car {
    field_a:[float];
    field_b:[float];
}

.

用于构建缓冲区的功能(尽管没有保存文件):

A function for building the buffer (although without the file saving):

bool save_flatbuf(string file_path, vector<double> vec_a, vector<double> vec_b) {
    flatbuffers::FlatBufferBuilder builder;

    auto vec_floats_a = builder.CreateVector(vec_a, vec_a.size());
    auto vec_floats_b = builder.CreateVector(vec_b, vec_b.size());

    auto mloc = CreateCar(builder, &vec_floats_a, &vec_floats_b);

    builder.Finish(mloc);

    // How to save it into a binary file with a list of "Cars"?
}

.

还有一个用于从二进制文件读取缓冲区后读取缓冲区的功能(不读取文件):

And a function for reading the buffer after it was read from the binary file (without the file reading):

bool read_flatbuf(string file_path) {

    // How to get the buffer pointer to a "Car" from a binary file with a "list of Cars" ? .

    vector<double> final_vec_a;
    vector<double> final_vec_b;

    auto car = GetCar(buffer_pointer);

    auto fa = car->field_a();
    auto fb = car->field_b();

    final_vec_a.resize(fa->size());
    for (int i = 0; i < fa->size(); i++) {
        final_vec_a[i] = fa->Get(i);
    }

    final_vec_b.resize(fb->size());
    for (int i = 0; i < fb->size(); i++) {
        final_vec_b[i] = fb->Get(i);
    }
}

不确定访问缓冲区信息的方法是否正确.例如,获取数组字段长度的方法.

Not sure if the way to access the buffer's info is correct. For instance the way to get the length of the array fields.

欢迎使用代码示例进行文件交互(在一个文件中写入/读取多个缓冲区).

Code examples for file interaction (write/read multiple buffers in one file) would be welcome.

推荐答案

我的解决方案是添加其他尺寸信息.

My solution is adding additional size information.

对于作家::

for (item : flatbuffer_list) {
   int size = item.GetSize();
   write (file, &size, sizeof(size));
   write (file, item.GetBufferPointer(), item.GetSize());
}

对于读者::

while(!eof(file)) {
   int size;
   read (file, &size, sizeof(size));
   read (file, buffer, size);
   auto item = GetItem(buffer);
}

这篇关于FlatBuffers:写入和读取二进制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆