(I think this is wrong way because binary could have a lot of null-s, but sting - don't)
C++ strings contain NUL characters just fine
But how to binary serialize in some buffer - there are no information. Could someone show how to do it?
Strings are also "some buffer". So using std::stringstream (which you likely saw) is already an answer to your question.
However, if you think a buffer is only when you have a naked array of char or something, you can "mount" a stream onto that. Now this is supposedly not too much work with std::streambuf, but the little I know about it is that it gets tricky around char_traits.
So, let's do the easy thing and use the Boost Iostreams types that already do this:
Live On Coliru
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/serialization/map.hpp>
#include <boost/serialization/string.hpp>
#include <iostream>
#include <iomanip>
namespace bio = boost::iostreams;
using Map = std::map<int, std::string>;
int main()
{
char buf[1024*10];
{
bio::stream<bio::array_sink> os(buf);
boost::archive::binary_oarchive oa(os);
oa << Map{
{1, "one"}, {2, "two"}, {3, "three"},
{4, "four"}, {5, "five"}, {6, "six"},
};
}
{
bio::stream<bio::array_source> is(buf);
boost::archive::binary_iarchive ia(is);
Map m;
ia >> m;
for (auto& [k,v] : m)
std::cout << " - " << k << " -> " << std::quoted(v) << "\n";
}
}
Printing
- 1 -> "one"
- 2 -> "two"
- 3 -> "three"
- 4 -> "four"
- 5 -> "five"
- 6 -> "six"