Is it possible to serialize and deserialize a class in C++?
I realize this is an old post but it's one of the first that comes up when searching for c++ serialization
.
I encourage anyone who has access to C++11 to take a look at cereal, a C++11 header only library for serialization that supports binary, JSON, and XML out of the box. cereal was designed to be easy to extend and use and has a similar syntax to Boost.
Boost is a good suggestion. But if you would like to roll your own, it's not so hard.
Basically you just need a way to build up a graph of objects and then output them to some structured storage format (JSON, XML, YAML, whatever). Building up the graph is as simple as utilizing a marking recursive decent object algorithm and then outputting all the marked objects.
I wrote an article describing a rudimentary (but still powerful) serialization system. You may find it interesting: Using SQLite as an On-disk File Format, Part 2.
The Boost::serialization
library handles this rather elegantly. I've used it in several projects. There's an example program, showing how to use it, here.
The only native way to do it is to use streams. That's essentially all the Boost::serialization
library does, it extends the stream method by setting up a framework to write objects to a text-like format and read them from the same format.
For built-in types, or your own types with operator<<
and operator>>
properly defined, that's fairly simple; see the C++ FAQ for more information.
I recommend Google protocol buffers. I had the chance to test drive the library on a new project and it's remarkably easy to use. The library is heavily optimized for performance.
Protobuf is different than other serialization solutions mentioned here in the sense that it does not serialize your objects, but rather generates code for objects that are serialization according to your specification.