class SomeClass: public ISerializable
{
public:
virtual void serializeTo(const std::stringstream& stream)
{
stream << mSomeValue;
stream << mSomeString;
}
int mSomeValue;
std::string mSomeString;
}
Simplest way to serialize data to network?
I was just wondering the simplest way to serialize data across a network. I have an abstract C++ class ISerializable, that defines two functions: virtual void serializeTo(const std::stringstream& stream) = 0; virtual void serializeFrom(const std::stringstream& stream) = 0; Base classes override these functions like so: Is it better to serialize the string length with the string? Any good resources worth reading? Thanks
---------------------http://www.stodge.net
Your basic approach looks fine. As things get bigger you may want to look into writing some code-generation tools to write the serialization stubs for you though as they tend to become a maintenance hassle.
You'll also find that serialization is relatively simple. de-serialization is trickier because you need to do the work of associating the data with whatever class it needs to go into yourself whereas the other way the compiler does much of the work for you.
For strings specifically both pascal-style (serializing the length explicitely) and c-style (using a terminator with no explicit length) have thier advantages. Pascal-style makes deserialization easier because you know up front how much memory you'll need (assuming you're allocating memory for it), however it makes serialization harder because you need to get that length (if you don't know it already) and put it the buffer. C style strings are nice if you're able to keep your deserialized pointers pointing directly into the recieve buffer. This creates data lifetime issues though and a good string class can eliminate the advantage. The upshot is basically do whatever is easiest or most natural for you.
You'll also find that serialization is relatively simple. de-serialization is trickier because you need to do the work of associating the data with whatever class it needs to go into yourself whereas the other way the compiler does much of the work for you.
For strings specifically both pascal-style (serializing the length explicitely) and c-style (using a terminator with no explicit length) have thier advantages. Pascal-style makes deserialization easier because you know up front how much memory you'll need (assuming you're allocating memory for it), however it makes serialization harder because you need to get that length (if you don't know it already) and put it the buffer. C style strings are nice if you're able to keep your deserialized pointers pointing directly into the recieve buffer. This creates data lifetime issues though and a good string class can eliminate the advantage. The upshot is basically do whatever is easiest or most natural for you.
-Mike
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement