enumerating over a structure fields in C enumerating over a structure fields in C sqlite sqlite

enumerating over a structure fields in C


It can be done with "macro magic" as you suggested:

For each struct, create a header file (mystruct-fields.h) like this:

FIELD(int,   field1)FIELD(int*,  field2)FIELD(char*, string1)

Then, in another header (mystruct.h) you include that as many times as you need:

#define FIELD(T,N) T N;struct mystruct {#include "mystruct-fields.h"};#undef FIELD#define FIELD(T,N) { STRINGIFY(T), STRINGIFY(N), offsetof(mystruct, N) },#define STRINGIFY1(S) #S#define STRINGIFY(S) STRINGIFY1(S)struct mystruct_table {  struct {    const char *type, *name;    size_t offset;  } field[];} table = {#include "mystruct-fields.h"  {NULL, NULL, 0}};#undef FIELD

You can then implement your reflection functions, using the table, however you choose.

It might be possible, using another layer of header file includes, to reuse the above code for any struct without rewriting it, so your top-level code might only have to say something like:

#define STRUCT_NAME mystruct#include "reflectable-struct.h"#undef STRUCT_NAME

Honestly though, it's easier for the people who come after you if you just write the struct normally, and then write out the table by hand; it's much easier to read, your IDE will be able to auto-complete your types, and prominent warnings in the comments should help prevent people breaking it in future (and anyway, you do have tests for this right?)


The way to do it is to have your struct in a database format or xml or a text file or whatever format you are comfortable with. And use a C program to write a .h file for each struct. The .h file contains the struct , an enum of the fields, and array of char containing the names of each field. From there you can build anything you need. Preferably using a program generator.


Take a look at Metaresc library. It provides reflection capabilities in plain C. Metadata of types definition could be derived either from custom macro language that replaces standard C type definition semantics or from compiler debug info. Sample app is provided in README.md