使用boost.python时c ++流有什么问题?

Nei*_*l G 14 c++ python boost-python

更新2:我不确定为什么这仍然被投票(2014年3月).自从我多年前提出这个问题以来,这似乎是固定的.确保您使用的是最新版本的boost.

更新:可能需要初始化C++流以格式化数字,并且在Python中加载共享库时不会进行初始化?

我在打电话

cout << 1 << "!" << endl; 
Run Code Online (Sandbox Code Playgroud)

在通过boost.python导出到共享库的方法中.它不打印任何东西,但如果我这样做

cout << "%" << "!" << endl; 
Run Code Online (Sandbox Code Playgroud)

有用.

这很重要因为我想这样做:

ostream& operator <<(ostream &os, const Bernoulli& b) {
    ostringstream oss;
    oss << b.p() * 100.0 << "%";
    return os << oss.str();
}
Run Code Online (Sandbox Code Playgroud)

通过这样做我暴露了:

BOOST_PYTHON_MODULE(libdistributions)
{
    class_<Bernoulli>("Bernoulli")
        .def(init<>())
        .def(init<double>())

        .def("p", &Bernoulli::p)
        .def("set_p", &Bernoulli::set_p)
        .def("not_p", &Bernoulli::not_p)

        .def("Entropy", &Bernoulli::Entropy)
        .def("KL", &Bernoulli::KL)
        .def(self_ns::str(self))
    ;
}
Run Code Online (Sandbox Code Playgroud)

但是当我str在伯努利对象上调用python中的方法时,我什么也得不到.我怀疑更简单的cout问题是相关的.

H. *_*ier 3

我不久前也遇到了这个问题,使用 self_ns ,如此处答案中概述的那样,在将 `__str__` 方法添加到 Boost Python C++ 类时构建问题

使用 self_ns 的原因由戴夫本人在这里解释:http://mail.python.org/pipermail/cplusplus-sig/2004-February/006496.html


只是为了调试,请尝试

inline std::string toString(const Bernoulli& b) 
{
   std::ostringstream s;
   s << b;
   return s.str(); 
}
Run Code Online (Sandbox Code Playgroud)

并替换.def(self_ns::str(self))

class_<Bernoulli>("Bernoulli")
[...]
.def("__str__", &toString)
Run Code Online (Sandbox Code Playgroud)