Boost.Python:无法包装 C++“operator<<”以在 Python 中公开打印功能

vid*_*vid 1 ostream boost-python python-2.7

我正在尝试包装一个使用 Boost.Python 处理二进制值的 C++ 类。对于此类,“<<”运算符已定义为

std::ostream &operator<<(std::ostream &output, const bin &inbin);
Run Code Online (Sandbox Code Playgroud)

我试着用

class_<bin>("bin", init<>())
    .def(str(self));
Run Code Online (Sandbox Code Playgroud)

但是,编译会引发此错误:

boost/python/def_visitor.hpp:31:9: error: no matching function for call to
‘boost::python::api::object::visit(boost::python::class_<itpp::bin>&) const’
Run Code Online (Sandbox Code Playgroud)

我不知道如何解决这个错误,有人知道吗?

参考:http : //www.boost.org/doc/libs/1_31_0/libs/python/doc/tutorial/doc/class_operators_special_functions.html

fed*_*pad 6

这似乎在以下 SO 帖子中有所涉及:
使用 boost.python 时 c++ 流有什么问题?
将 `__str__` 方法添加到 Boost Python C++ 类时的构建问题

所以,根据之前的帖子,你应该尝试替换

.def(str(self));  
Run Code Online (Sandbox Code Playgroud)

.def(self_ns::str(self)); 
Run Code Online (Sandbox Code Playgroud)

或者

.def(self_ns::str(self_ns::self))  
Run Code Online (Sandbox Code Playgroud)

在这些情况下,它似乎已经解决了同样的问题。

如果上述方法不起作用,请尝试编写自定义包装器。例如,您可以将 print_wrap 函数定义为:

#include <sstream>
std::string print_wrap(const classname &c)
{
  std::ostringstream oss;
  oss << "HelloWorld " << c.var1 << " " << c.var2;
  return oss.str();
}
Run Code Online (Sandbox Code Playgroud)

然后在class_<classname>("py_classname")定义中使用,

.def("__str__", &print_wrap)
Run Code Online (Sandbox Code Playgroud)

然后在 Python 中你应该能够得到

>>> obj = py_classname(1,2)  #var1=1, var2=2
>>> print obj
>>> HelloWorld 1 2
Run Code Online (Sandbox Code Playgroud)