On Thursday 27 September 2001 21:29, Wayne E. Van Loon Sr. wrote:

[...copying structs...]

> If I understand you, this means that my code might fail when both ends
> of a fifo were not compiled by the same gcc version or when both ends
> of a network are not compiled by the same gcc version or are differing
> platforms.

That's right; structs may turn out different with different compilers. 
The main reason is different datatype alignment rules.


> How do you do it?

One *relatively* safe method is to use "natural" alignment; keep elements 
of the same size and type together, and insert explicit padding elements 
where required. (Most compilers will normally align datatypes to adresses 
that are multiples of the size of one element of the data type.)

However, DON'T rely on this one if you don't know which compilers your 
code will be built on! I know of compilers that don't pack structures 
this way - and alignment rules differ between CPU families.


A somewhat safer method is to use compiler specific aligment directives 
in the code. That way, you can make sure that elements are always aligned 
back-to-back. Be careful though; some CPUs will crash if your data is 
incorrectly aligned! (68k pre 68030 [or was it 68020?] for example.)


A nearly fool-proof method is to use inline functions or macros to access 
elements inside byte arrays. Correctly implemented, this method even 
ensures endian correctness, and usually compiles into virtually no code, 
unless byte order inversion is required. Unless you're going to send data 
between different endian CPUs, you can just make sure that your "encoded" 
endian is the same as the CPU's native endian.

Example:

/*
 * Writes "val" in big endian format into 'buf'.
 * Returns number of bytes written.
 */
int write_int(char *buf, int val)
{
        buf[0] = val & 0xff;
        buf[1] = (val>>8) & 0xff;
        buf[2] = (val>>16) & 0xff;
        buf[3] = (val>>24) & 0xff;
        return 4;
}

Note that for total portability, your should verify that sizeof(int) 
really is 4, as it might be smaller on some systems... (It's not a 
problem if it's bigger - this code will still write a 32 bit int.)


//David Olofson --- Programmer, Reologica Instruments AB

.- M A I A -------------------------------------------------.
|      Multimedia Application Integration Architecture      |
| A Free/Open Source Plugin API for Professional Multimedia |
`----------------------------> http://www.linuxdj.com/maia -'
.- David Olofson -------------------------------------------.
| Audio Hacker - Open Source Advocate - Singer - Songwriter |
`-------------------------------------> http://olofson.net -'

-- [rtl] ---
To unsubscribe:
echo "unsubscribe rtl" | mail [EMAIL PROTECTED] OR
echo "unsubscribe rtl <Your_email>" | mail [EMAIL PROTECTED]
--
For more information on Real-Time Linux see:
http://www.rtlinux.org/

Reply via email to