打印Boost Python对象

Bar*_*rry 6 c++ python boost-python

我有一个Boost Python对象

py::object obj = whatever();
Run Code Online (Sandbox Code Playgroud)

我想用普通的python规则打印它.

// I want the effect of print 'My object is ', obj
std::cout << "My object is " << obj << std::endl;
Run Code Online (Sandbox Code Playgroud)

这不会使用巨大的编译器转储进行编译.我该怎么做呢?

Bar*_*rry 10

Boost.Python没有附带,operator<<(ostream&, const object&)但我们可以编写自己的模仿Python本来会做什么:调用str:

namespace py = boost::python;

std::ostream& operator<<(std::ostream& os, const py::object& o)
{
    return os << py::extract<std::string>(py::str(o))();
}
Run Code Online (Sandbox Code Playgroud)