I could use some advice for a problem that I've had on my mind for years. I'm looking for a black box function that will examine a memory block of a known structure and output a list of IDs that point to any members that have changed. I have a strong feeling that this problem has been solved by many people before me but I've never seen any solution. I'm looking for an elegant solution that requires little to no source code changes when a structure member is changed, added, or removed. Please follow my problem description below to get an idea of what I'm looking for.
I have a largish C structure containing data members of various types and sizes. The structure definition will probably have to change over the course of project development. Data packaged in the structure will arrive at some processing function. The processing function will always keep a copy of the previously processed structure so that a compare operation can be used to identify any structure members that have changed. There is such a large number of members that my quest is to automate as much as possible the ID and comparison operations. Not automating would require the programmer to redo the comparison which would be a giant if/elseif/else statement with customized comparison for each structure member. That would invite mistakes if not done accurately.
Below is what I've hacked out so far using the C preprocessor. It quickly points to various problems that makes the problem seem like too much work for the preprocessor (like, for example, it won't work for c[3]). Maybe a code generation step using perl or python would work better. I thought I'd check with the experts before working on it further.
#define MEMBER(t,v) t v; size_t size_ ## v; size_t id_ ## v
typedef struct { MEMBER(int,i); MEMBER(char,c); MEMBER(float,f); } STRUCT;
STRUCT s;
s.size_i = sizeof(s.i); s.id_i = offsetof(STRUCT,i); s.size_c = sizeof(s.c); s.id_c = offsetof(STRUCT,c); s.size_f = sizeof(s.f); s.id_f = offsetof(STRUCT,f);
printf("I: Size = %d, ID = %d\n",s.size_i,s.id_i); printf("C: Size = %d, ID = %d\n",s.size_c,s.id_c); printf("F: Size = %d, ID = %d\n",s.size_f,s.id_f);
Thanks - JJS