15

更新 2:我不确定为什么这仍然被赞成(2014 年 3 月)。自从我多年前问过这个问题以来,这似乎已经解决了。确保您使用的是最新版本的 boost。

更新:也许需要初始化 C++ 流以格式化数字,并且在 Python 中加载共享库时不会发生初始化?

我打电话

cout << 1 << "!" << endl; 

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

cout << "%" << "!" << endl; 

有用。

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

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

我通过这样做暴露了这一点:

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))
    ;
}

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

4

3 回答 3

3

前段时间我也遇到过这个问题,使用 self_ns 作为答案中的概述将`__str__`方法添加到Boost Python C ++类时的构建问题

使用 self_ns 的原因是 Dave 自己在这里解释的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(); 
}

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

class_<Bernoulli>("Bernoulli")
[...]
.def("__str__", &toString)
于 2012-11-12T10:56:29.470 回答
2

您是否尝试过使用boost::format?由于您已经在使用boost,所以应该不会太麻烦。

boost::format( "%d%%" ) % ( b.p() * 100.0 )

另一件事,尝试std::endl显式传递给 output os

于 2011-01-07T14:21:12.227 回答
0

您是否尝试过在使用 .str() 方法之前刷新流?

oss << b.p() * 100.0 << "%" << std::flush;
于 2011-01-11T19:55:22.710 回答