How wrap std::istream and std::ostream with pybind11?

  c++, pybind11

I have two function in cpp that get the state of my class and read state from my class.

writeBinary(std::ostream& s) 
readBinary(std::istream& s)

I want to have a python function that I can do

binary_state = class_a.writeBinary()
class_b = class_a.readBinary(binary_state)
class_a == class_b

I have been trying to get pybind11 working with this. I have tried to have a wrapper that writeBinary will return string but I have no luck.
Here is what I tried to convert osstream to string

std::string writeBinaryWrapper(){
       std::stringstream binary_outfile;
       return binary_outfile.str();

but I got UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 143: invalid start byte error for this attemp.
And I cannot figure out a way to wrap pybind11 with std::ostream or std::istream.

    .def("writeBinary", []() {
        std::ostringstream out;
        py::scoped_ostream_redirect redirect{
            py::module_::import("io").attr("BytesIO") // Python output

Can anyone help me with this? How can I get a pybind so I can write a class to binary and then read from binary to recreate the class?

Source: Windows Questions C++