The easiest serialization method for strings or other blobs with variable size is to serialize first the size as you serialize integers, then just copy the content to the output stream.
When reading you first read the size, then allocate the string and then fill it by reading the correct number of bytes from the stream.
with ostream/istream
native way with ostream/istream for example class MyClass with height,width,name fields.
classMyClass { public: int height; int width; std::string name; }
std::ostream& MyClass::serialize(std::ostream &out)const{ out << height; out << ','//number seperator out << width; out << ','//number seperator out << name.size(); //serialize size of string out << ','//number seperator out << name; //serialize characters of string return out; } std::istream& MyClass::deserialize(std::istream &in){ if (in) { int len=0; char comma; in >> height; in >> comma; //read in the seperator in >> width; in >> comma; //read in the seperator in >> len; //deserialize size of string in >> comma; //read in the seperator if (in && len) { std::vector<char> tmp(len); in.read(tmp.data() , len); //deserialize characters of string name.assign(tmp.data(), len); } } return in; }
boost::archive::binary_iarchive ia(stream); Camera new_cam; ia & (new_cam); std::cout << new_cam << std::endl; } catch (Poco::Exception& exc) { app.logger().log(exc); } }
notes on std::string
Even know you have seen that they do the same, or that .data() calls .c_str(), it is not correct to assume that this will be the case for other compilers. It is also possible that your compiler will change with a future release.
2 reasons to use std::string:
std::string can be used for both text and arbitrary binary data.