Skip to content

Instantly share code, notes, and snippets.

@Warchant
Created January 20, 2017 07:39
Show Gist options
  • Save Warchant/390b182cc00e6371e2e3e32aa63c4cdc to your computer and use it in GitHub Desktop.
Save Warchant/390b182cc00e6371e2e3e32aa63c4cdc to your computer and use it in GitHub Desktop.
Flatbuffer example
cmake_minimum_required (VERSION 2.8.11)
project (fbtest)
SET( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14" )
add_executable(write1 write1.cpp)
target_include_directories(write1 PUBLIC
"/home/bogdan/tools/flatbuffers/include"
)
target_link_libraries(write1 LINK_PUBLIC flatbuffers)
add_executable(read1 read1.cpp)
target_include_directories(read1 PUBLIC
"/home/bogdan/tools/flatbuffers/include"
)
target_link_libraries(read1 LINK_PUBLIC flatbuffers)
#include <iostream>
#include <fstream>
#include "schema_generated.h"
using namespace Soramitsu::Sumeragi;
int main(){
FILE* file = fopen("out", "rb");
if(!file) perror("can't open out file");
unsigned int size = 0;
fread(&size, sizeof(size), 1, file);
char *buffer = new char[size];
fread(buffer, size, 1, file);
auto config = GetConfig(buffer);
auto me = config->me();
std::cout << "ip: " << me->ip()->str() << std::endl;
std::cout << "name: " << me->name()->str() << std::endl;
std::cout << "publicKey: " << me->publicKey()->str() << std::endl;
std::cout << "privateKey: " << me->privateKey()->str() << std::endl;
if(buffer) delete [] buffer;
fclose(file);
}
// Example IDL file for our monster's schema.
namespace Soramitsu.Sumeragi;
table GroupMember{
ip:string;
name:string;
publicKey:string;
}
table Me{
ip:string;
name:string;
privateKey:string;
publicKey:string;
}
table Config{
me:Me;
group:[GroupMember];
}
root_type Config;
#include <iostream>
#include <fstream>
#include "schema_generated.h"
using namespace Soramitsu::Sumeragi;
int main(){
flatbuffers::FlatBufferBuilder builder;
auto ip = builder.CreateString("127.0.0.1");
auto name = builder.CreateString("da77880a3da4");
auto priv = builder.CreateString("cPY84e0BXGUHBjT4QdlPI0LI3BPIfUfSZjB8jdWURkNQ+pEagT/ysrewbt2YUo/Qbfd5vczW5oDooGSNUBTj9g==");
auto pub = builder.CreateString("u7X/zQ/Dq21WW7YH4rbkpiCYJXjPxk5t3qNDKiVwBx8=");
auto me = CreateMe(builder, ip, name, priv, pub);
auto groupmember = CreateGroupMember(builder, ip, name, pub);
std::vector<flatbuffers::Offset<GroupMember>> group;
group.push_back(groupmember);
auto _group = builder.CreateVector(group);
auto config = CreateConfig(builder, me, _group);
builder.Finish(config);
uint8_t *buf = builder.GetBufferPointer();
unsigned int size = builder.GetSize();
FILE* file = fopen("out", "wb");
if(!file) perror("write: can't open file out");
fwrite(&size, sizeof(size), 1, file);
fwrite(buf, size, 1, file);
fclose(file);
std::cout << "Success\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment