Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print Boost Python object

I have a Boost Python object

py::object obj = whatever();

I want to print it using normal python rules.

// I want the effect of print 'My object is ', obj
std::cout << "My object is " << obj << std::endl;

This does not compile with a huge compiler dump. How do I do this?

like image 458
Barry Avatar asked Dec 16 '14 19:12

Barry


1 Answers

Boost.Python doesn't come with an operator<<(ostream&, const object&) but we can write our own to mimic what Python would do natively: call str:

namespace py = boost::python;

std::ostream& operator<<(std::ostream& os, const py::object& o)
{
    return os << py::extract<std::string>(py::str(o))();
}
like image 92
Barry Avatar answered Sep 29 '22 02:09

Barry