How to find space occupied by a struct field and the padding between it and the next field?

104 Views Asked by At

So if I have a struct like so:

//fwd decl
class Payload_t;

//msg class for ipc
struct Msg
{
    uint16_t  Hdr;
    Payload_t Payload; //whatever type I want here
}; 

I want to get the size of Msg::Hdr including any padding prior to the next field Msg::Payload.

I want this because I am working in an embedded system that using the QNX Neutrino OS. The OS is a microkernel message passing OS. A common technique is to design all messages with a short header that contains special information that users of my library code do not need to be aware of, and a payload (the part the users care about). The QNX IOV facility allows a great performance improvement in cases like this by cutting down on copying. Their API works like this:

Msg msg;
iov_t iovReq[2];

//the below causes problems because it doesn't include alignment padding
SETIOV( iovReq + 0, &msg.Hdr,     sizeof( msg.Hdr     ) ); 
SETIOV( iovReq + 1, &msg.Payload, sizeof( msg.Payload ) );

However, I found that:

sizeof( Msg::Hdr ) + sizeof( Msg::Payload ) != sizeof( Msg )

How do I do this? I've seen some tricky stuff but not sure of the most proper way to do this. I suspect the answer will involve some combination of: sizeof, alignof, or the macro offsetof.

QNX Multipart Messages with IOV http://www.qnx.com/developers/docs/6.6.0.update/#com.qnx.doc.neutrino.getting_started/topic/s1_msg_Multipart_messages.html

1

There are 1 best solutions below

1
On BEST ANSWER

To me, that sounds like a simple:

std::size_t const FirstAndPadding = offsetof(A, Second) - offsetof(A, First);

Why you'd want that, is another question.