Why consider flatbuffer over json
How much is flatbuffer faster protobuf
Primay differences between protbuf and flatbuffers
Today, I am going to demonstrate how to use flatbuffers to auto-generate enum/constants for different languages like c++, java, python, and so on.
Clone flatbuffers
$ git clone https://github.com/google/flatbuffers
$ cd flatbuffers
Depending on your platform, use one of e.g.
Start to build$ cmake -G "Unix Makefiles"$ cmake -G "Visual Studio 10"$ cmake -G "Xcode"
$ make
After making it, there is one of executable files, called flatc. Now, we can use flatc to genereate different source files for different language using flatbuffers's interface definition language(IDL).Create an IDL file
$ vi resultcode.fbs
namespace tzutalin.common;Use the below command to generate its c++ header, python, and Java file.enum ResultCode { SUCCESS = 0, TIME_OUT, UNKNOWN_ERROR }
$ ./flatc --cpp --python --java -b resultcode.fbs
After generating, it creates ./resultcode_generated.h, ./tzutalin/common/ResultCode.py, and ./tzutalin/common/ResultCode.java.
resultcode_generated.h:
ResultCode.py// automatically generated by the FlatBuffers compiler, do not modify#ifndef FLATBUFFERS_GENERATED_RESULTCODE_TZUTALIN_COMMON_H_#define FLATBUFFERS_GENERATED_RESULTCODE_TZUTALIN_COMMON_H_#include "flatbuffers/flatbuffers.h"namespace tzutalin {namespace common {enum ResultCode {ResultCode_SUCCESS = 0,ResultCode_TIME_OUT = 1,ResultCode_UNKNOWN_ERROR = 2,ResultCode_MIN = ResultCode_SUCCESS,ResultCode_MAX = ResultCode_UNKNOWN_ERROR};inline const char **EnumNamesResultCode() {static const char *names[] = { "SUCCESS", "TIME_OUT", "UNKNOWN_ERROR", nullptr };return names;}inline const char *EnumNameResultCode(ResultCode e) { return EnumNamesResultCode()[static_cast<int>(e)]; }} // namespace common} // namespace tzutalin#endif // FLATBUFFERS_GENERATED_RESULTCODE_TZUTALIN_COMMON_H_
# automatically generated by the FlatBuffers compiler, do not modify# namespace: commonclass ResultCode(object):SUCCESS = 0TIME_OUT = 1UNKNOWN_ERROR = 2
ResultCode.java:
// automatically generated by the FlatBuffers compiler, do not modifypackage tzutalin.common;public final class ResultCode {private ResultCode() { }public static final byte SUCCESS = 0;public static final byte TIME_OUT = 1;public static final byte UNKNOWN_ERROR = 2;public static final String[] names = { "SUCCESS", "TIME_OUT", "UNKNOWN_ERROR", };public static String name(int e) { return names[e]; }}
No comments:
Post a Comment