使用boost.python时c ++流有什么问题? [英] what is wrong with c++ streams when using boost.python?

查看:84
本文介绍了使用boost.python时c ++流有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我在打电话

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

在通过boost.python导出到共享库的方法中.它什么也不会打印,但是如果我打印

in a method that is exported to a shared library via boost.python. It doesn't print anything, but if I do

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

有效.

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

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

但是当我在Bernoulli对象上用python调用str方法时,我什么也没得到.我怀疑较简单的cout问题是相关的.

but when I call the str method in python on a Bernoulli object, I get nothing. I suspect the simpler cout problem is related.

推荐答案

我前一段时间也遇到了这个问题,使用了答案中概述的self_ns

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的原因 http://mail.python.org/pipermail/cplusplus-sig/2004-February/006496.html

The reason for using self_ns is explained by Dave himself here 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(); 
}

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

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

这篇关于使用boost.python时c ++流有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆