简体   繁体   English

Flatbuffers:在 C++ 中写入读取二进制文件问题?

[英]Flatbuffers: write read binary file issue in c++?

My schema, encoder and decoder looks as below.我的架构、编码器和解码器如下所示。

Schema :架构:

namespace Myclient.sample;
table Person {
  age: short;
}
root_type Person;

Encoder:编码器:

int main(int argc, char *argv[])
{            
        flatbuffers::FlatBufferBuilder builder(1024);
        auto name = builder.CreateString("Mr Test");
        PersonBuilder mybuilder(builder);
        mybuilder.add_age(20);
        auto orc = mybuilder.Finish();
        builder.Finish(orc);
        uint8_t *buf = builder.GetBufferPointer();
        int size = builder.GetSize();
        ofstream wf(argv[1], ios::out | ios::binary);           
        wf.write((char*) &buf, size);   // overwrite
        wf.close();            
        return 0;
}

Decoder:解码器:

int main(int argc, char *argv[])
{
    //Read BIN file
    std::ifstream infile;
    infile.open(argv[1], std::ios::binary | std::ios:: in);
    infile.seekg(0, std::ios::end);
    int length = infile.tellg();
    infile.seekg(0, std::ios::beg);
    char *data = new char[length];
    infile.read(data, length);
    infile.close();

    flatbuffers::Verifier verifier(reinterpret_cast< unsigned char*> (data), length);
    bool ok = VerifyPersonBuffer(verifier);

    cout << "   verify value2: " << ok << endl;
    auto per = GetPerson(data);
    if (per)
    {
        cout << " person decoded" << endl;
        cout << "age is " << per->age() << endl;
    }
    return 0;
}

output of decoder: verify value2: 0 person decoded解码器的输出:验证值2:0人解码

Issue: could not decoded.问题:无法解码。 is there any issue with biniary file read write, or schema definition.二进制文件读写或架构定义是否有任何问题。 please help.请帮忙。 Thanks.谢谢。

wf.write((char*) &buf, size); will happily write the address of buf to that file followed by a large amount of garbage.会很高兴地将buf地址写入该文件,然后是大量垃圾。 The compiler was trying to warn you but you shut it up without reading the error.编译器试图警告您,但您没有阅读错误就将其关闭。 Change to buf and at least that problem is solved. buf ,至少这个问题解决了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM