How to deal with C structs with runtime determined layouts?
In my code, I need to deal with one of two structs that share almost all of the members, but their offsets can only be determined at runtime. Something like:
struct type1 {int a, char b[8], int c};
struct type2 {int a, char b[16], int c};
There's nothing I can do about the layout of these structs, because it's dictated by hardware.
So every time I want to access a member I would need to do something like:
void foo(void *data)
{
if (is_type1)
((struct type1 *)(data))->c = 5;
else
((struct type2 *)(data))->c = 5;
}
And that is not very elegant.
I was wondering if there is some recipe for a more elegant handling of this situation, besides hiding all this ugliness in macros, which is the solution I will resort to in a开发者_如何学编程bsence of a better one.
Thanks.
If you can't change the order, I would join them into the same struct as a union:
struct type12 { union { struct type1 type1; struct type2 type2; } types; int type; };
void foo(struct type12 *data)
{
if (data->type == 1)
data->types.type1.c = 5
else
data->types.type2.c = 5;
}
Perhaps not a big improvement, but you can avoid the type casts...
Move the shared members into a seperate struct, and use that as the first member of the two types. This has the advantage that you don't have to test types (or even care about them) in order to read/write the shared data.
#include <stdio.h>
struct shared_data {
int a;
int c;
};
struct type1 {
struct shared_data shared;
char b[2];
};
struct type2 {
struct shared_data shared;
char b[4];
};
void foo(void *data)
{
((struct shared_data*)(data))->c = 5;
}
int main(int argc, char** argv) {
struct type1 a;
struct type2 b;
foo(&a);
foo(&b);
printf("A: %d\nB: %d\n", a.shared.c, b.shared.c);
}
Outputs
A: 5
B: 5
精彩评论