This is the mail archive of the mailing list for the GCC project.

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: alignment: x86 vs ppc

Hi John,

Your question is not a GCC question, it is a general programming question.
There are other forums that are more appropriate for your question.  I don't
say this to chastise you, but rather to help you locate a better source of

That being said...

So if I understand correctly, your communication protocol is passing "raw
structs" around.

In general, a struct is not platform agnostic.  By platform I mean "OS + a
particular version of a particular compiler".

However, you can make a struct platform agnostic using this method (assuming
C-ish pseudocode):

typedef char byte;
struct MessageRecord
  byte mID[4]; // big-endian int32
  byte mAction[2]; // big-endian int16
  byte mValue[8]; // big-endian int64

struct Message
  int mID;
  short mAction;
  long mValue;

void OutputMessage(int fd, struct Message* msg)
  struct MessageRecord rec;
  HtonInt32(&rec.mID, msg->mID);
  HtonInt16(&rec.mAction, msg->mAction);
  HtonInt64(&rec.mValue, msg->mValue);
  write(fd, &rec, sizeof rec);

void InputMessage(int fd, struct Message* msg)
  struct MessageRecord rec;
  read(fd, &rec, sizeof rec);
  NtohInt32(&msg->mID, rec.mID);
  NtohInt16(&msg->mAction, rec.mAction);
  NtohInt64(&msg->mValue, rec.mValue);

That way the MessageRecord is platform agnostic and has a canonical "over
the wire format" (which also serves equally well as a canonical "on disk
file format"), regardless of source or destination, and does not suffer from
intra-member padding, end-of-structure alignment padding, and alignment

Note:  The Hton (host to network) and Ntoh (network to host) functions do
the correct endian packing for your platform and the used in the local
application Message.  I leave those as an exercise.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]