Quote:
I don't remember the details well enough to repeat any of it convincingly, but I was convinced when I read it. In real projects, it is a lot easier to wrap __attribute__ into a preprocessor macro (to make it properly conditional on the compiler/architecture in a semi portable project) than to do that with #pragma Quote:
In the quoted code, the packed attribute applies only to i and not to i1 Other methods of specifying packed (appearing elsewhere in this thread) apply the packed attribute to the entire struct. Quote:
Quote:
Quote:
|
Quote:
--- rod. |
Code:
typedef struct network_format { |
I agree that your suggestion will probably work with respect to packing/alignment (most of your suggestion seems to relate to byte-ordering; a different but related subject) on most architectures, there is nothing to ensure that the packing of the structure will necessarily be the same as a deliberately packed structure. Without the directive not to, padding bytes may be added in any part of the struct. In practice, AFAIK, this would rarely be done between char type elements, but again, this is not guaranteed. Nested structures make the problem even more difficult.
If the solution comes down to breaking every structure element into its respective char-sized elements, then I see the solution as much worse than the problem. I would say that the __attribute__((packed)) directive preserves the purpose of the C struct, by allowing an expression that plainly reflects the nature of the data. Unfortunately, it forces us to know when it is necessary, and embeds architecture-specific features into our source code. --- rod. |
Sorry, from your answer I couldn't decide if my answer helped or not. Maybe I should summarize it in plain text: define a special structure only for the network traffic, in this structure every data-element that isn't aligned on its natural alignment (for elementary types it is an offset that is divisible with their size) are to be replaced with char-arrays. To convert from/to this special structure, you have to write conversion functions.
PS: The opposite problem may arise if the network protocol demands gaps between the fields that your compiler may or may not provide; you can add 'char unused_nnn [gapsize]' fields to be sure. PPS: And obviously types short/int/long long mustn't be used in the network structure, int16_t/int32_t/int64_t are you friends. |
All times are GMT -5. The time now is 05:34 AM. |