//This is how I implemented this. But still have few issues/questions, please help!
#define VECTOR_SIZE 5 //I initially set this to 1000, then reduced it to 5 for the issue that I have encountered.
//To start creating a buffer, create an instance of FlatBufferBuilder
flatbuffers::FlatBufferBuilder fbb;
//How do I populate &part_buf programmatically using application data (1000 elements)
fbb.StartVector(VECTOR_SIZE, sizeof(Recipient));
printf("\nsizeof(Recipient)=%d", sizeof(Recipient));
std::string display_name = "d#";
std::string email = "u-";
std::string i_str;
for (int i = 0; i < VECTOR_SIZE; i++)
{
i_str = std::to_string(i);
display_name.append(i_str);
email.append(i_str);
email.append(email_domain);
fbb.PushBytes(reinterpret_cast<const uint8_t *>(display_name.c_str()), display_name.length());
fbb.PushBytes(reinterpret_cast<const uint8_t *>(email.c_str()), email.length());
display_name.clear();
email.clear();
display_name = "d#";
email = "u-";
}
auto partVector = fbb.EndVector(VECTOR_SIZE);
EmailHeaderBuilder emailHeader(fbb);
emailHeader.add_recipients(partVector);
auto ehLoc = emailHeader.Finish();
FinishEmailHeaderBuffer(fbb,ehLoc);
printf("\nSize of buffer=%d",fbb.GetSize());
const char *fileName = "emailheaderData.bin";
bool result = flatbuffers::SaveFile(fileName, (const char *)fbb.GetBufferPointer(), (size_t)fbb.GetSize(), true); //I verified this by opening emailHeaderData.bin file and it is written appropriately.
printf("\nSaveFile Result = %d", result);
std::string buffer;
result = flatbuffers::LoadFile(fileName, true, &buffer);
printf("\nLoadFile Result = %d", result);
printf("\nLength of buffer(read)=%d", buffer.length()); //This result matches to the result returned by fbb.GetSize()
const EmailHeader *emailHeader = GetEmailHeader((buffer.c_str()));
const flatbuffers::Vector<flatbuffers::Offset<Recipient>> *recipLocation = emailHeader->recipients();
for (size_t i = 0; i < VECTOR_SIZE; i++)
{
const Recipient *aRecipLoc = recipLocation->Get(i);
std::cout << "[" << i << "]-Display Name" << aRecipLoc->display_name() << std::endl; //crashes here with this (A)
std::cout << "[" << i << "]-Email" << aRecipLoc->email()->c_str() << std::endl;
}
(A) Unhandled exception at 0x000F4141 in PlaywithFB.exe: 0xC0000005: Access violation reading location 0x756FF420. Inside flatbuffers.h header, line #146, call to EndianScalar() inside ReadScalar() function. I tried various alternates to fix this without any luck.
(B) I also tried using 'auto' types when collecting result from GetEmailHeader() function and emailHeader->recipients() function calls, but the issue stayed.
(C) Also, do I have to stick to PushBytes(...) calls in order to build the vectors dynamically? Do we have an alternate approach to this?
Could you help me figure out the possible issue in this case?
Thank you,
Hardik