Have seen various code around where one read data into a char or void and then
cast it to a struct. Example is parsing of file formats where data has fixed offsets.
Example:
struct some_format {
char magic[4];
uint32_t len;
uint16_t foo;
};
struct some_format *sf = (struct some_format*) buf;
To be sure this is always valid one need to align the struct by using __attribute__((packed)).
struct test {
uint8_t a;
uint8_t b;
uint32_t c;
uint8_t d[128];
} __attribute__((packed));
When reading big and complex file formats this surely makes things much simpler. Typically
reading media format with structs having 30+ members etc.
It is also easy to read in a huge buffer and cast to proper type by for example:
struct mother {
uint8_t a;
uint8_t b;
uint32_t offset_child;
};
struct child {
...
}
m = (struct mother*) buf;
c = (struct child*) ((uint8_t*)buf + mother->offset_child);
Or:
read_big_buf(buf, 4096);
a = (struct a*) buf;
b = (struct b*) (buf + sizeof(struct a));
c = (struct c*) (buf + SOME_DEF);
...
It would also be easy to quickly write such structures to file.
My question is how good or bad this way of coding is. I am looking at various data structures and would use the best way to handle this.
- Is this how it is done? (As in: is this common practice.)
- Is
__attribute__((packed))always safe? Is it better to useWhat was I thinking about?, Thanks @Amardeepsscanf.- Is it better to make functions where one initiates structure with casts and bit shifting.
- etc.
As of now I use this mainly in data information tools. Like listing all structures of a certain type with their values in a file format like e.g. a media stream. Information dumping tools.
void... Or even acharif it reads more than one byte. Maybe into achar *or avoid *, though, as long as the buffer it points to is big enough...