I was reading this article (Struct iteration through (ab)use of the preprocessor), where the author uses x-macros and offsetof
to add metadata to structs which would allow their members to be easily serialized, accessed by name, etc. But it's only implemented for primitive struct elements.
Is it possible to expand this to structs containing nested struct, also? I.e. something which would allow simple de/serialialization of something like:
struct some_struct {
int x, y, z;
};
struct data {
int number;
struct some_struct something;
};
I've noticed the author states this at the beginning:
At this stage, the structs only consist of primitive elements (int, float, char, etc). Handling nested structs, unions, bitfields and pointers would require additional work (that may be the subject of a future post).
Is something like this possible using the C preprocessor?
(Clarification)
To make it clearer, I'd like to see if there is a way which would allow me to:
a) define the struct
, and
b) create meta data for textual serialization/deserialization
if possible in one step.
Everything that you asked for is implemented here https://github.com/alexanderchuranov/Metaresc
Here is a sample app:
#include <metaresc.h>
TYPEDEF_STRUCT (some_struct_t,
int x,
int y,
int z,
);
TYPEDEF_STRUCT (data_t,
int number,
(struct some_struct_t, something),
);
int main (int argc, char * argv[])
{
data_t data = { 1, { 2, 3, 4 } };
MR_PRINT ("data = ", (data_t, &data));
return (EXIT_SUCCESS);
}
Expected output:
data = {
.number = 1,
.something = {
.x = 2,
.y = 3,
.z = 4
}
}