【发布时间】:2010-12-06 01:10:03
【问题描述】:
更新 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))
;
}
但是当我在 python 中对 Bernoulli 对象调用 str 方法时,我什么也得不到。我怀疑更简单的 cout 问题是相关的。
【问题讨论】:
-
我对 iostreams 和 boost.python 没有问题...也许问题来自更微妙的错误?但是,文档中的技术 (1dl.us/dAD) 对我不起作用,我不得不写
.def("__str__", &print_wrapper<Bernouilli>)。self_ns是什么?另外,在你的方法中,为什么不只是{return os << b.p() * 100.0 << "%"; }? -
@rafak 这个问题解释了通过 ostringstream 进行操作的原因:stackoverflow.com/questions/2249018/…
-
@rafak
print_wrapper在哪里定义?我在 boost 中找不到它。 -
我应该说它是我的:template
inline std::string print_wrapper(const C& obj) { std::ostringstream os;操作系统
标签: c++ python boost-python