C struct Alignement avr-gcc / Linux

Hi,

I am building a small GUI on Linux to enter paramters for control loops runnning on an ATMega128. As the protocol is bi-directionnal I thought I could use the same C functions on both sides to serialize/deserialize the data.

The way I send the data over the UART is that I just copy byte per byte the struct containing the data.

Unfortunately, the alignement on the PC is different, causing small items to be aligned on a 4byte boundary.

Did someone already solve this problem without having to duplicate the struct definition in some way ?

Thanks Martial

Reply to
Martial Chateauvieux
Loading thread data ...

Google for keywords like "attribute packed".

Peter

--
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.779 / Virus Database: 526 - Release Date: 19/10/04
Reply to
moocowmoo

That's exactly the method you're *not* supposed to do it. C structs are inherently unportable, so trying to directly exchange their memory representations between different platforms is begging for trouble. Never assume anything but the compiled program containing them will ever be able to make sense out of its internal data structures.

The proper method is to have pairs of (un)marshalling functions at each end of the link, which translate between internal representation and a well-defined "transport format". You will also hear this called "(de)serialization". Within some limitations (most importantly, CHAR_BIT == 8), these (un)marshalling functions can be written to be portable across the link: they have to translate your entire data to a completely well-defined stream of single bytes. I.e.: send each element separately, and cut it into bytes based on value, not on memory layout of the hosting CPU.

--
Hans-Bernhard Broeker (broeker@physik.rwth-aachen.de)
Even if all the snow were burnt, ashes would remain.
Reply to
Hans-Bernhard Broeker

Reply to
Martial Chateauvieux

ElectronDepot website is not affiliated with any of the manufacturers or service providers discussed here. All logos and trade names are the property of their respective owners.