Reflection support in C

Viewed 25809

I know it is not supported, but I am wondering if there are any tricks around it. Any tips?

10 Answers

For similar reasons to the author of the question, I have been working on a C-type-reflection-API along with a C reflection graph database format and a clang plug-in that writes reflection metadata.

The intent is to use the C reflection API for writing serialization and deserialization routines, such as mappers for ASN.1, function argument printers, function proxies, fuzzers, etc. Clang and GCC both have plugin APIs that allow access to the AST but there currently is no standard graph format for C reflection metadata.

The proposed C reflection API is called Crefl:

https://github.com/michaeljclark/crefl

The Crefl API provides runtime access to reflection metadata for C structure declarations with support for arbitrarily nested combinations of: intrinsic, set, enum, struct, union, field (member), array, constant, variable.

  • The Crefl reflection graph database format for portable reflection metadata.
  • The Crefl clang plug-in outputs C reflection metadata used by the library.
  • The Crefl API provides task-oriented query access to C reflection metadata

A C reflection API provides access to runtime reflection metadata for C structure declarations with support for arbitrarily nested combinations of: intrinsic, set, enum, struct, union, field, array, constant, variable. The Crefl C reflection data model is essentially a transcription of the C data types in ISO/IEC 9899:9999.

  • C intrinsic data types.
    • integer types.
    • floating-point types.
    • complex number types.
    • boolean type.
  • nested struct, union, field, and bitfield
  • arrays and pointers
  • typedef type aliases
  • enum and enum constants
  • functions and function parameters
  • const, volatile and restrict qualifiers
  • GNU-C style attributes using (__attribute__).

The library is still a work in progress. The hope is to find others who are interested in reflection support in C.

Parsers and Debug Symbols are great ideas. However, the gotcha is that C does not really have arrays. Just pointers to stuff.

For example, there is no way by reading the source code to know whether a char * points to a character, a string, or a fixed array of bytes based on some "nearby" length field. This is a problem for human readers let alone any automated tool.

Why not use a modern language, like Java or .Net? Can be faster than C as well.

Related