Re: structure alignment
From: Jack Masters (jcfmasters_at_yahoo.com)
Date: 09/08/05
- Next message: Jan Panteltje: "Re: Anybody faimilar with mozilla sourcecode?"
- Previous message: Basile Starynkevitch [news]: "Re: Anybody faimilar with mozilla sourcecode?"
- In reply to: Sagaert Johan: "Re: structure alignment"
- Next in thread: Phil Frisbie, Jr.: "Re: structure alignment"
- Reply: Phil Frisbie, Jr.: "Re: structure alignment"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Thu, 08 Sep 2005 11:24:38 +0200
Sagaert Johan wrote:
> "David Schwartz" <davids@webmaster.com> wrote in message
> news:dfohh5$vnr$1@nntp.webmaster.com...
>
>>"Sagaert Johan" <sagaert.j AT belgacom.net> wrote in message
>>news:431f3ec8$0$28236$ba620e4c@news.skynet.be...
>>
>>
>>>i need it becorse i receive an arry of bytes from a serial comm routine
>>>that
>>>is copied into the structure (enum )
>>
>> When you copy it into the structure, put everything where it goes. You
>>*cannot* rely on a structure having a particular representation in memory
>
> at
>
>>the byte level.
>>
>> DS
>>
>>
>
> When i learned C i came across a section that showed the layout in memory
> follows the layout of the structure, the only thing i came across si that
> byte ordering for int is different on some platforms.
> So far i never came into problems using this technique.
>
> struct s_remote
> {
> char name[10];
> char prefix[20];
> int flags;
> } ;
>
> union u_remote
> {
> unsigned char B[sizeof s_remote];//as bytes
> struct s_remote S; //as structure
> } ;
>
> union u_remote myvar;
>
> //receive from a remote device through comport
> while (n< sizeof myvar)
> {
> myvar.B[n]= received_byte();
> n++;
> }
>
> // using my data
> printf(" data=%s",myvar.S.prefix);
>
>
>
This is how we did all the comms and IPC work under CCPM, and there is
nothing wrong with it on 99% of platform/compiler combinations. Provided
you are using the right compiler options, like no aggressive
optimizations, and byte-aligned struct members of course. However, on
the remaining 1% it might bomb on you (e.g. your structure defines a
32-bit int that is not dword-aligned, the compiler generates a 32-bit
fetch, and the CPU can't handle that).
This is why the current generation gurus agitates against this concept.
If you are writing something for a single platform, and for *in-house
use only*, fine. If you want to release the code into the wild, and make
it anywhere near portable, don't use this.
J.
- Next message: Jan Panteltje: "Re: Anybody faimilar with mozilla sourcecode?"
- Previous message: Basile Starynkevitch [news]: "Re: Anybody faimilar with mozilla sourcecode?"
- In reply to: Sagaert Johan: "Re: structure alignment"
- Next in thread: Phil Frisbie, Jr.: "Re: structure alignment"
- Reply: Phil Frisbie, Jr.: "Re: structure alignment"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|