Jan Bottorff wrote:
My opinion REALLY is you should NEVER depend on a struct to have a
specific memory layout, and you should have functions/objects/macros
that pack and unpack a byte pointer to/from your unpacked structure.
Explicit code to define the packing and unpacking means you’re
documenting what the expected binary layout is. I don’t believe the C
spec says anything about how compiler implementations will pack
structures.
Worse than that, the C standards don’t even mandate whether bitfields
are laid out left-to-right or right-to-left. So:
struct Example {
int one : 1;
int rest : 31;
};
The standard leaves it up to the implementation to decide whether “one”
is bit 0 or bit 31.
Most kernel code has very limited cross-platform requirements. so we can
make assumptions based on that.
A better strategy might also be to have things like protocol messages
defined in some description language, and you preprocess that language
into .c/h files for your specific platform. This has the huge
advantage you can also process the message descriptions into the
language used by the your network sniffer, so if you change a message
during development, the code and the tools all automatically stay in sync.
I’ve seen that done, for hardware that ran on several wildly different
platforms. It can be quite successful.
If you’ve ever looked inside the code for the X Window System, they make
a very serious attempt to handle wildly different architectures. It’s a
hairy tangled mess of ifdefs and options, but it’s flexible.
–
Tim Roberts, xxxxx@probo.com
Providenza & Boekelheide, Inc.