In our project, the sender - legacy unchangeable - C code, serialize the C struct
in the following fashion. Note the Message struct
is unpacked.
struct Message {
uint32_t field1 __attribute__ ((aligned (4)));
uint16_t field2 __attribute__ ((aligned (2)));
};
Sender
char *buf = getBuffer();
Message *m = (Message *)buf;
m->field1 = 0x11;
m->field2 = 0x22;
m->field1 = htonl(m->field1);
m->field2 = htons(m->field2);
Receiver
Now how do we de-serialize this at the receiver (C++). I am given to understand that the following is not valid?
void process (char *p)
{
Message *m = (Message *)p;
m->field1 = htonl(m->field1);
m->field2 = htons(m->field2);
}
Is the below okay?
void process (char *p)
{
static std::aligned_storage<MAX_SIZE, std::max_align_t>::type buffer;
Message *m = new ((void *)&buffer) Message;
memcpy(m, p, sizeof(Message));
m->field1 = htonl(m->field1);
m->field2 = htons(m->field2);
}
Is there another better way?