How can I add reflection to a C++ application?

前端 未结 28 1630
感动是毒
感动是毒 2020-11-21 11:25

I\'d like to be able to introspect a C++ class for its name, contents (i.e. members and their types) etc. I\'m talking native C++ here, not managed C++, which has reflection

28条回答
  •  梦如初夏
    2020-11-21 11:42

    The information does exist - but not in the format you need, and only if you export your classes. This works in Windows, I don't know about other platforms. Using the storage-class specifiers as in, for example:

    class __declspec(export) MyClass
    {
    public:
        void Foo(float x);
    }
    

    This makes the compiler build the class definition data into the DLL/Exe. But it's not in a format that you can readily use for reflection.

    At my company we built a library that interprets this metadata, and allows you to reflect a class without inserting extra macros etc. into the class itself. It allows functions to be called as follows:

    MyClass *instance_ptr=new MyClass;
    GetClass("MyClass")->GetFunction("Foo")->Invoke(instance_ptr,1.331);
    

    This effectively does:

    instance_ptr->Foo(1.331);
    

    The Invoke(this_pointer,...) function has variable arguments. Obviously by calling a function in this way you're circumventing things like const-safety and so on, so these aspects are implemented as runtime checks.

    I'm sure the syntax could be improved, and it only works on Win32 and Win64 so far. We've found it really useful for having automatic GUI interfaces to classes, creating properties in C++, streaming to and from XML and so on, and there's no need to derive from a specific base class. If there's enough demand maybe we could knock it into shape for release.

提交回复
热议问题