Re: Issues with memcpy

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

 



Hi Javier,

>So what is the best way to copy a struct to a byte array without copying empty aligned spaces?  I'm doing now the ugly way, just pointing to each field each time and copying to the buffer.  It's for transmition purposes.

Thanks for the tidbit as to why you are doing this.

I recommend:  data for saving to files or transmission over the wire should be saved/sent in a canonical format.  And data being restored from a file or received from the wire should be read/received in that canonical format and turned back into a data structure.

That means use htons and htonl for writing (16-bit, 32-bit respectively).  For reading it's ntohs and ntohl.

Should you rely on buffering, such as FILE and IP's Nagle Algorithm for buffering to handle your buffering needs, or should you roll-your-own?  I cannot say.

If you do roll your own, I recommend doing something like this (I'm assuming C; in C++ I'd do it different):

typedef struct
{
	char ctype[1];
	char itype[4];
	char itype2[4];
} t_st_record;

And make two routines:
void SerializeT_St(t_st* p, t_st_record* r);
void DeserializeT_St(t_st* p, t_st_record* r);

The SerializeT_St routine copies the fields over one-by-one, using htons and htonl appropriately, producing the byte-oriented populated t_st_record data structure.

The DeserializeT_St routine reconstitutes the t_st structure field-by-field from the "raw bytes" represented in the t_st_record input.  Using ntohs and ntohl appropriately.

(If you have IEEE 754 float and doubles, you'll have to figure out how you want to canonically send them.)

The t_st_record is a holding record for the canonical (persistant or tranmission) data.  It's life span is pretty ephemeral.  Just long enough to read in and regurgitate into a t_st.  Or just long enough to be populated by a t_st and spat out.

The t_st structure is the "live data" internal to your application.  The t_st_record is the "persistent store/transmission format" external to your application.

If you do NOT roll your own buffering, I recommend doing something like this (again, assuming C):

void SerializeT_St(t_st* p, FILE* out);
void DeserializeT_St(t_st* p, FILE* in);

Or if you are using FD's instead of FILE's:

void SerializeT_St(t_st* p, int outFd);
void DeserializeT_St(t_st* p, int inFd);

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