Wush Wu — written Nov 7, 2015 — source
This post shows how to serialize a C++ object into a R raw vector object—the base type used by the internal R serialization—and how to deserialize it.
The following example shows a toy C++ class and the related serialize/deserialize functions. It shows how one can use the cereal header-only C++ library and Boost Iostreams in Rcpp. It relies on the corresponding Rcereal and BH packages which need to be installed. It also requires compilation with support for the C++11 standard, which we enable via the corresponding Rcpp plugin.
Thanks to how Rcpp and R interact, the compiler will automatically find the header file according to
// [[Rcpp::depends(Rcereal)]] and
[[Rcpp::depends(BH)]]. The member function
void serialize(Archive & archive) tells cereal how to serialize and deserialize the C++ class
will be saved and loaded if they are passed to the argument
cereal::BinaryOutputArchive oarchive(ss); defines an instance of bineary archive. The
oarchive(my_instance); archives the instance of
MyClass to the
output stream and writes the data to the
cereal::BinaryInputArchive iarchive(ss); defines an instace of bineary archive. The
iarchive(my_instance); reads the data from the
and restores the content to the instance of
Let’s try these two functions in R:
 01 00 00 00 02 00
As you can see, the instance of
MyClass is successfully saved to
v and loaded from
The API of cereal is similar to the one of Boost Serialization. The main difference is that the cereal prefers using
() to send data to archives. Please
visit the transition from Boost page for more details about the difference between cereal and
The most important advantage may be that cereal is header-only, which makes it easier to write portable package with cereal compared to Boost Serialization.