Re: alignment: x86 vs ppc

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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
information.

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
constraints.

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.

HTH,
--Eljay


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux