C++ Runtime Reflection
Eclipsed Engine
C++ can't look at its own types at runtime, but an editor needs to. I designed and built the reflection system that lets Eclipsed Engine's editor show, edit and save any component without knowing anything about it.

At a glance

Version 1: making it work

Early on we knew we needed a way to edit positions and other values from the editor. In my first system, every editable value was wrapped in its own templated type, hidden behind a macro called SERIALIZED_FIELD.
class ObstacleSpawner : public Eclipse::Component
{
    COMPONENT_BASE_2(ObstacleSpawner, 3)
public:
    void Start() override;
    void Update() override;
private:
    SERIALIZED_FIELD(Eclipse::Assets::Prefab, ObstaclePrefab);
    SERIALIZED_FIELD(float, ObstacleSpawnInterval, 2);
    float obstacleSpawnTimer = 0.f;
};
It worked, and it let the team move on to other parts of the engine. The cost was that each field stored its own copy of the type and variable metadata. Every instance of a class carried the same data again and again, and SpriteRenderer2D grew to about 912 bytes per instance.

We accepted that trade-off at first. As the engine grew, so did the components, and it was time to fix it properly.

Version 2: making it right

Before rewriting anything I wrote down what the first version had taught me:
  • Metadata belongs to the type, not the instance. A field's name and type are the same for every instance, so they should be stored once.
  • No wrapper types. A reflected field should be a normal member variable.
  • It has to be extensible. We wanted to mark fields for more than just the editor.

That led me to move reflection out of the classes and into the build. Fields are marked with an attribute such as [[SerializeField]], and before compiling, a tool scans the headers and generates metadata for each marked class. That metadata exists once per type, no matter how many instances there are.

The same component now looks like this:
class ObstacleSpawner : public Eclipse::Component
{
    MAKE_REFLECTABLE(ObstacleSpawner);
    REFLECTION_FLAG(COMPONENT);

    COMPONENT_BASE_2(ObstacleSpawner, 3)
public:
    void Start() override;
    void Update() override;
private:
    [[SerializeField]]
    Eclipse::Assets::Prefab ObstaclePrefab;

    [[SerializeField]]
    float ObstacleSpawnInterval = 2;

    float obstacleSpawnTimer = 0.f;
};
The class still needs a couple of macros to set itself up, but the fields are plain variables again.

Generating the metadata

I wrote a tool called HeaderTool that scans every header in a project and generates a registration file for each reflected type. For each field it records the name, type, size and offset into the class. That is everything the editor needs to find a field in any instance and read or write it.

Regex on its own can't read C++, so the tool does some work first:
  • It blanks out comments and strings, so commented-out code isn't reflected by mistake.
  • It tracks curly brackets, so it knows where a class ends and ignores fields of nested structs.
  • Classes opt in with MAKE_REFLECTABLE, and only fields with an attribute are reflected.

This runs at build time, never while the game is running. The engine is reflected when the CMake project is rebuilt, and the game when its dynamic library is rebuilt.

This is the code generated for ObstacleSpawner:
template<> struct ReflectionRegistrar<ObstacleSpawner>
{
    static inline void Register()
    {
        Reflection::ReflectionRegistry::RegisterType(
            TypeEntry{
                .name = "ObstacleSpawner",
                .size = sizeof(ObstacleSpawner),
                .id = Type::GetTypeID<ObstacleSpawner>(),
                .create = [](){ return reinterpret_cast<void*>(new ObstacleSpawner); },
                .createAtAddress = [](unsigned char* addr){ return reinterpret_cast<void*>(new (addr)ObstacleSpawner); },
                .destroy = [](void* data){ delete reinterpret_cast<ObstacleSpawner*>(data); },
                .flag = static_cast<Reflection::ReflectionFlags>(1),
                .fieldOrder = { "ObstaclePrefab", "ObstacleSpawnInterval" }
            }
        );

        {
            FieldEntry entry =
            {
                .name = "ObstacleSpawnInterval",
                .owner = "ObstacleSpawner",
                .offset = offsetof(ObstacleSpawner, ObstacleSpawnInterval),
                .size = sizeof(ObstacleSpawner::ObstacleSpawnInterval),
                .type = Type::GetTypeID<decltype(ObstacleSpawner::ObstacleSpawnInterval)>()
            };

            Reflection::ReflectionRegistry::RegisterType<decltype(ObstacleSpawner::ObstacleSpawnInterval)>();
            entry.attributeContainer.Add<SerializeField>();

            Reflection::ReflectionRegistry::RegisterField(
                "ObstacleSpawner",
                entry
            );
        }

        // ...and one block like this for every other reflected field
    }
};
Because the generated code uses sizeof, offsetof and decltype, the compiler fills in the real layout. The tool only has to find names. It never has to work out sizes or offsets itself.

Registering without anyone remembering to

The tool also generates one file that calls every type's Register method from the constructor of a static object. Static objects are constructed before main() runs, so nobody has to call an init function or add a new component to a list. If a component is reflected, it is registered.
struct ComponentsStaticInitiator
{
    ComponentsStaticInitiator()
    {
        ReflectionRegistrar<Canvas>::Register();
        ReflectionRegistrar<SpotLight2D>::Register();
        ReflectionRegistrar<AudioEmitter>::Register();
        ReflectionRegistrar<Camera>::Register();
        ReflectionRegistrar<RigidBody2D>::Register();
        ReflectionRegistrar<AmbientLight2D>::Register();
        ReflectionRegistrar<DirectionalLight2D>::Register();
        ReflectionRegistrar<PointLight2D>::Register();
        ReflectionRegistrar<ParticleSystem2D>::Register();
        ReflectionRegistrar<Transform2D>::Register();
        ReflectionRegistrar<SpriteRenderer2D>::Register();
    }
};

inline ComponentsStaticInitiator __componentsStaticInititator = {};
The game is a dynamic library that the editor loads, so it works a little differently. There the tool generates an exported RegisterReflectedTypes function, which the editor calls right after loading the library.

Reading and writing fields

Once every type is registered, accessing a field takes a lookup and an offset. If the field has an OnChange attribute, its callback runs after the value is set.
void Set(const std::string& typeName, const std::string& fieldName, void* obj, const void* data)
{
    const FieldEntry& field = ReflectionRegistry::GetField(typeName, fieldName);
    ::memcpy(reinterpret_cast<char*>(obj) + field.offset, data, field.size);

    const OnChange* onChange = field.attributeContainer.TryGet<OnChange>();
    if (onChange)
    {
        onChange->event(obj);
    }
}

void* Get(const std::string& typeName, const std::string& fieldName, void* obj)
{
    const FieldEntry& field = ReflectionRegistry::GetField(typeName, fieldName);
    return reinterpret_cast<char*>(obj) + field.offset;
}
This is all the editor needs to show and change a value without knowing the class it is editing.

Lists need a bit more. A std::vector can't be edited with just an offset and a size, so for vector fields the system also stores a small set of functions: get size, get element, resize and erase. With those the editor can edit any list without knowing what is in it.

Extending it with attributes

An attribute is just a struct. These are some of the ones the engine has today:
struct SerializeField {};

struct Range
{
    float min, max;
};

struct Step
{
    float step;
};

struct OnChange
{
    std::function<void(void*)> event;
};
The tool doesn't need to know what an attribute means. It copies the name and arguments straight into the generated code, so [[SerializeField, Step(0.1f)]] becomes:
entry.attributeContainer.Add<SerializeField>();
entry.attributeContainer.Add<Step>(0.1f);
Each field stores its attributes by type, and any system can ask whether a field has one. This is how the inspector decides how much a value changes when you drag it:
const Step* stepAttr = attrs.TryGet<Step>();
if (stepAttr) step = stepAttr->step;
Adding a new attribute means declaring a struct and reading it where it's needed. The reflection system itself never has to change. That was the extensibility goal from version 2.

The results

  • About 70% smaller components. SpriteRenderer2D went from about 912 bytes per instance to 272. Type data now lives in one central registry.
  • Plain variables. Reflected fields are normal members, used directly in gameplay code.
  • One system, many users. The inspector, JSON serialization and game DLL loading all read the same metadata.
  • Easy to extend. A slider or a change callback is one attribute away, like [[SerializeField, OnChange(OnChangeSprite)]].

Trade-offs and next steps

I chose a pattern-matching tool over a full C++ parser to keep the build simple and fast. That choice has known limits, and this is how I would address them:
  • It doesn't fully parse C++. Unusual declarations like function pointers or C-style arrays aren't picked up. Moving HeaderTool to libclang would give it a real syntax tree.
  • Types are looked up by name. Two reflected classes with the same name in different namespaces would collide. Registering by fully qualified name or by type ID would fix that.
  • Setting a value copies raw bytes. That is fine for floats and vectors, but not for types that own memory. Generating a typed copy function per field, like the vector helpers, would make it safe.

The source code for the reflection module is on GitHub.