Reputation: 159
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
Issue: could not decoded. is there any issue with biniary file read write, or schema definition. please help. Thanks.
Upvotes: 0
Views: 491
Reputation: 30850
wf.write((char*) &buf, size);
will happily write the address of buf
to that file followed by a large amount of garbage. 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.
Upvotes: 2