Enumerate members of a structure?

前端 未结 6 890
渐次进展
渐次进展 2021-01-13 10:02

Is there a way to enumerate the members of a structure (struct | class) in C++ or C? I need to get the member name, type, and value. I\'ve used the following sample code b

相关标签:
6条回答
  • 2021-01-13 10:10

    To state the obvious, there is no reflection in C or C++. Hence no reliable way of enumerating member variables (by default).

    If you have control over your data structure, you could try a std::vector<boost::any> or a std::map<std::string, boost::any> then add all your member variables to the vector/map.

    Of course, this means all your variables will likely be on the heap so there will be a performance hit with this approach. With the std::map approach, it means that you would have a kind of "poor man's" reflection.

    0 讨论(0)
  • 2021-01-13 10:17

    simplest way - switch to Objective-C OR Objective-C++. That languages have good introspection and are full-compatible with C/C++ sources.

    also You can use m4/cog/... for simultaneous generation structure and his description from some meta-description.

    0 讨论(0)
  • 2021-01-13 10:17

    It feels like you are constructing some sort of debugger. I think this should be doable if you make sure you generate pdb files while building your executable.

    Not sure in what context you want to do this enumeration, but in your program you should be able to call functions from Microsofts dbghelp.dll to get type information from variables etc. (I'm assuming you are using windows, which might of course not be the case)

    Hope this helps to get you a little bit further.

    Cheers!

    0 讨论(0)
  • 2021-01-13 10:19

    You can specify your types in an intermediate file and generate C++ code from that, something like COM classes can be generated from idl files. The generated code provides reflection capabilities for those types.

    I've done something similar two different ways for different projects:

    • a custom file parsed by a Ruby script to do the generation
    • define the types as C# types, use C#'s reflection to get all the information and generate C++ from this (sounds convoluted, but works surprisingly well, and writing the type definitions is quite similar to writing C++ definitions)
    0 讨论(0)
  • 2021-01-13 10:22

    Since C++ does not have reflection builtin, you can only get the information be teaching separately your program about the struct content.

    This can be either by generating your structure from a format that you can use after that to know the strcture information, or by parsing your .h file to extract the structure information.

    0 讨论(0)
  • 2021-01-13 10:31

    Boost has a ready to use Variant library that may fit your needs.

    0 讨论(0)
提交回复
热议问题