In the past, speaking of cross-language tools to serialize and auto-generate structured data, you might use Protobuf to do that, Recently, I start to use flatbuffers to serialize/deserialize and auto-generate my data structure. There are a lot of comparisons on Protobuf, json, and flatbuffers, you can refer to the below links:
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.
$ cmake -G "Unix Makefiles"
$ cmake -G "Visual Studio 10"
$ cmake -G "Xcode"
Start to build
$ 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;
enum ResultCode { SUCCESS = 0, TIME_OUT, UNKNOWN_ERROR }
Use the below command to generate its c++ header, python, and Java file.
$ ./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:
// 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_
ResultCode.py
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: common
class ResultCode(object):
SUCCESS = 0
TIME_OUT = 1
UNKNOWN_ERROR = 2
ResultCode.java:
// automatically generated by the FlatBuffers compiler, do not modify
package 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]; }
}