Serializing a c++ class [duplicate]
Possible Duplicate:
How to serialize in c++ ?
I have a class
Class Person
{
int age;
char *name;
char* Serialize()
{
//Need to convert age and name to char* eg:21Jeeva
}
void DeSerialize(char *data)
{
//Need to populate age and name from the data
}
};
In C# we can use MemoryStream,BinrayWriter/BinaryReader to achieve this. In c++ somewhere i found we can use iostream to achieve it. But couldnt able to get a proper example of it.
The purpose of the code is after calling serialize i am going to send开发者_StackOverflow中文版 the data over socket and in receiving end ill call DeSerialize to populate the members back.
You could take a look at Boost.Serialization. If you only need a simple text-serialization based on iostreams, you probably want to overload the stream extraction operators. For serialization this could look like this:
std::ostream & operator<<(std::ostream & stream, const Person & person) {
stream << person.age << " " << person.name;
return stream;
}
You have to make this function a friend of Person
for this to work.
For deserialization, you would use this:
std::istream & operator>>(std::istream & stream, Person & person) {
stream >> person.age >> person.name;
return stream;
}
Using these, you can do the following:
Person fred;
fred.name = "Fred";
fred.age = 24;
std::stringstream buffer;
buffer << fred << std::endl;
Person fred_copy;
buffer >> fred;
You can find a small working example here.
Overloading these operators has the advantage that you can for instance use std::copy
with an std::ostream_iterator
to serialize an entire collection of Persons in one statement.
You can use following wrapper to convert any datatype to character stream:
template<class TYPE>
string ToChar (const TYPE& value)
{
stringstream ss;
ss << value;
return ss.str();
}
You can use the string
object the way you want; like convert into char stream using c_str()
or copy into array and so on.
精彩评论