Boost logo

Boost Users :

Subject: Re: [Boost-users] alignment question
From: Larry Evans (cppljevans_at_[hidden])
Date: 2010-01-03 12:27:12


On 12/23/09 10:37, Stefan Strasser wrote:
> Am Wednesday 23 December 2009 01:40:39 schrieb Slawomir Lisznianski:
>> template <typename T>
>> struct envelope
>> {
>> size_t len = sizeof(T);
>> // <--- compiler may pad here, hence this doesn't work...
>> T body;
>> };
>>
>> So, given an arbitrary type T, we want to create an envelope that will
>> have the size of T immediately before it, with no padding between len
>> and body.
>>
>> The user would then be able to:
>>
>> envelope<MyStruct> env;
>>
>> env.body.x = ...
>>
>> send(env);
>
> you can't make the compiler skip alignment, so if you want to keep the user
> interface, you have to redirect the accesses to a char array.
> something like this:
>
> template<class T,std::size_t HeaderSize>
> struct envelope_base{
> char data[HeaderSize + sizeof(T)];
> };
>
> template<class T>
> struct envelope : envelope_base<T,sizeof(size_t)>{
> envelope()
> : len(*reinterpret_cast<size_t *>(data))
> , body(*reniterpret_cast<T *>(data+sizeof(size_t)){
> len=sizeof(T);
> }
> size_t &len;
> T &body;
> };
>
> template<class T,size_t HeaderSize>
> void send(envelope_base<T,HeaderSize> const &);
>
>> I'm curious if anyone has run into something similar and have a clean
>> solution. Our code currently has to defer to temporary buffers and
>> memcpy'ing data back to it.
>
> not sure how "clean" that solution is. it might technically even be undefined
> behaviour.
There's the composite_tagged_seq<all_of_packed,...> in the
composite_tagged_seq.zip file here:

http://www.boostpro.com/vault/index.php?&directory=Data%20Structures

However, it essentially does the memcpy'ing the data which you dislike;
however, as Stefan points out, you've got to do that if you plan on
actually using the data as intended (i.e. properly aligned).
However, the composite_tagged_seq template makes the packing
and unpacking pretty easy (I think).

I've an updated version of the code if you're interested.

-Larry


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net