Jump to content

  • Log In with Google      Sign In   
  • Create Account

sizeof() not working ?!?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
20 replies to this topic

#21 Trienco   Crossbones+   -  Reputation: 2195

Like
0Likes
Like

Posted 30 January 2013 - 02:58 PM

Last time I needed to serialize data to send and receive messages, I ended up building a stream like container and forwarding one operator (&, as inspired by boost) to either << or >> depending on stream type. So each message had one function that would stuff all members into the container or get it out. A few overloads for C-strings, arrays, etc., however no handling of endianness (at least it was never used, there was a very inefficient template to reverse byte order).

 

It wasn't bullet proof and because of all the templates the user could still put in entire structs (so it was his job to worry about padding). The core of each "stream" was essentially something like

 

template <typename T>
OutStream& operator<<(const T& data)
{
    buffer.resize( buffer.size() + sizeof(T) );
    memcpy(buffer + pos, &data, sizeof(T));
    pos += sizeof(T);
}
 
//some overloads of <<
 
//same for InStream and >>
 
template<typename T>
inline InStream& operator&(InStream& stream, T& data) { return stream >> data; }
 
 
template<typename T>
inline OutStream& operator&(OutStream& stream, T& data) { return stream << data; }

 

For each message there was a function like

 

template<class StreamType>
bool packUnpack(StreamType& stream)
{
     stream & member1 & member2 & member3 & member4;
     return !stream.fail();
}

 

Adding a member still required to change that function, but reading/writing was consistent, sizes were determined automatically (so using types with fixed size is important) and it worked well enough for what it was used for.


f@dzhttp://festini.device-zero.de

Sponsor:



Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS