0

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?

MGH
  • 475
  • 7
  • 19
  • The alignment requirement of Message and char are different. `Message m; memcpy(&m, p, sizeof(Message));`, I don't think you need to use aligned_storage. – Tony J Apr 10 '17 at 21:32
  • @Tony thanks! The intend of aligned storage was as a static buffer for all types of messages. So I think scheme 2 is good and scheme 1 is invalid. – MGH Apr 10 '17 at 21:38
  • 1
    ok, that makes sense. Side note, static buffer is not thread-safe. – Tony J Apr 10 '17 at 21:45

0 Answers0