简体   繁体   English

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

[英]what is wrong with c++ streams when using boost.python?

Update 2: I'm not sure why this is still being upvoted (March 2014). 更新2:我不确定为什么仍要对此进行投票(2014年3月)。 This appears to be fixed since I asked this question many years ago. 自从我多年前问这个问题以来,这似乎是固定的。 Make sure you're using a recent version of boost. 确保您使用的是Boost的最新版本。

UPDATE: Perhaps C++ streams need to be initialized in order to format numbers, and the initialization is not happening when the shared library is loaded in Python? 更新:也许需要对C ++流进行初始化才能格式化数字,并且在Python中加载共享库时初始化没有发生吗?

I am calling 我在打电话

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

in a method that is exported to a shared library via boost.python. 通过boost.python导出到共享库的方法中。 It doesn't print anything, but if I do 它什么也不会打印,但是如果我打印

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

it works. 有用。

This is important because I want to do this: 这很重要,因为我想这样做:

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

I exposed that by doing this: 我这样做是暴露了这一点:

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

but when I call the str method in python on a Bernoulli object, I get nothing. 但是当我在Bernoulli对象上的python中调用str方法时,什么也没得到。 I suspect the simpler cout problem is related. 我怀疑较简单的cout问题是相关的。

I also run into this problem a while ago, using self_ns as outlined in the answers here Build problems when adding `__str__` method to Boost Python C++ class 不久前,我也遇到了这个问题,使用了self_ns,如此处的答案中所述。在向Boost Python C ++类添加`__str__`方法时生成问题

The reason for using self_ns is explained by Dave himself here http://mail.python.org/pipermail/cplusplus-sig/2004-February/006496.html Dave自己在此处解释了使用self_ns的原因,网址为http://mail.python.org/pipermail/cplusplus-sig/2004-February/006496.html


Just for the sake of debugging, please try 只是为了调试,请尝试

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

And replace .def(self_ns::str(self)) with 并将.def(self_ns::str(self))替换为

class_<Bernoulli>("Bernoulli")
[...]
.def("__str__", &toString)

Have you tried using boost::format instead? 您是否尝试过使用boost::format Since you are already using boost , it shouldn't be too much of a hassle. 由于您已经在使用boost ,所以它不会太麻烦。

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

Another thing, try passing std::endl explicitly to the output os . 另一件事,请尝试将std::endl显式传递给输出os

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

oss << b.p() * 100.0 << "%" << std::flush;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM