[英]what is wrong with c++ streams when using boost.python?
更新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))
;
}
但是当我在Bernoulli对象上的python中调用str
方法时,什么也没得到。 我怀疑较简单的cout问题是相关的。
不久前,我也遇到了这个问题,使用了self_ns,如此处的答案中所述。在向Boost Python C ++类添加`__str__`方法时生成问题
Dave自己在此处解释了使用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();
}
并将.def(self_ns::str(self))
替换为
class_<Bernoulli>("Bernoulli")
[...]
.def("__str__", &toString)
您是否尝试过使用boost::format
? 由于您已经在使用boost
,所以它不会太麻烦。
boost::format( "%d%%" ) % ( b.p() * 100.0 )
另一件事,请尝试将std::endl
显式传递给输出os
。
在使用.str()方法之前,您是否尝试过刷新流?
oss << b.p() * 100.0 << "%" << std::flush;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.