开发者

Serializing a c++ class [duplicate]

This question already has answers here: Closed 11 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜