使用python作为配置文件,生成c++ struct以及字段反射
需要c++ 版本至少为17
用于Aether项目ECS系统生成带有反射信息的component struct
需要安装clang-format,并使其在环境变量中
1.修改 aether_reflect/config.py
class Config:
def __init__(self):
self.root=""
g_config=Config()
g_config.root="D:/dev/AetherReflect"
def get_config():
return g_config
把 "D:/dev/AetherReflect" 改成你的安装路径
- 生成
cd /path/to/AetherReflect
> python3 aether_reflect/entry.py <python_cfg_dir> <output_dir> <variant_output_path> <variant_include_path>
example
python3 aether_reflect/entry.py test_res/ test_output test_output/reflect_variant.h "reflect_variant.h"
输入
filename="example.h"
comment="""
example of a struct definition
"""#optional
includes="""
#include <string>
"""#optional
structs=[
{
"name":"::Aether::Person",
"comment":"a struct for test",# optional
"fields":[
{
"name":"tag",
"type":"::std::string",
"comment":"tag field"#optional
}
],
"constructors":[
"""
Person(const std::string& _tag):
tag(_tag)
{}
""",
]
}
]#optional
输出
// File: example.h
// Generated by Aether Reflect
//
// example of a struct definition
#pragma once
#include "reflect_variant.h"
#include <string>
namespace Aether {
// a struct for test
struct Person {
Person(const std::string &_tag) : tag(_tag) {}
::std::string tag;
};
} // namespace Aether
namespace Aether {
struct Reflect<::Aether::Person> {
static constexpr const inline char *name = "::Aether::Person";
static constexpr const inline char *comment = "a struct for test";
static constexpr const inline size_t field_count = 1;
static constexpr const inline char *field_names[] = {
"tag",
};
static constexpr const inline char *field_types[] = {
"::std::string",
};
static constexpr const inline char *field_comments[] = {
"tag field",
};
static ReflectVariant get(const ::Aether::Person &obj,
const std::string &key) {
if (key == "tag") {
return obj.tag;
}
}
static void set(::Aether::Person &obj, const std::string &key,
const ReflectVariant &value) {
if (key == "tag") {
obj.tag = std::get<::std::string>(value);
}
}
};
} // namespace Aether
输出variant
#pragma once
#include <variant>
#include <string>
namespace Aether {
template <typename T> struct Reflect {};
using ReflectVariant = std::variant<uint64_t, ::std::string>;
} // namespace Aether