相关疑难解决方法(0)

将`__str__`方法添加到Boost Python C++类时构建问题

我已经开始尝试使用boost python并遇到问题.我试图将一个C++类暴露给python,这没有任何问题.但我似乎无法实现__str__类的功能而不会出现我不明白的构建错误.

我正在使用boostpro的boost 1_42 prebuild.我使用cmake和vs2010编译器构建库.

我有一个非常简单的设置.头文件(tutorial.h)如下所示:

#include <iostream>
namespace TestBoostPython{
    class TestClass {
        private:
            double m_x;
        public:
            TestClass(double x);
            double Get_x() const;
            void Set_x(double x);
    };
    std::ostream &operator<<(std::ostream &ostr, const TestClass &ts);
};
Run Code Online (Sandbox Code Playgroud)

和相应的cpp文件看起来像:

#include <boost/python.hpp>
#include "tutorial.h"

using namespace TestBoostPython;

TestClass::TestClass(double x)
{
    m_x = x;
}

double TestClass::Get_x() const
{
    return m_x;
}
void TestClass::Set_x(double x)
{
    m_x = x;
}

std::ostream &operator<<(std::ostream &ostr, const TestClass &ts)
{
    ostr << ts.Get_x() << "\n";
    return ostr;
} …
Run Code Online (Sandbox Code Playgroud)

python boost-python

18
推荐指数
2
解决办法
2997
查看次数

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

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

更新:可能需要初始化C++流以格式化数字,并且在Python中加载共享库时不会进行初始化?

我在打电话

cout << 1 << "!" << endl; 
Run Code Online (Sandbox Code Playgroud)

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

cout << "%" << "!" << endl; 
Run Code Online (Sandbox Code Playgroud)

有用.

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

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

通过这样做我暴露了:

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))
    ;
}
Run Code Online (Sandbox Code Playgroud)

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

c++ python boost-python

14
推荐指数
1
解决办法
2128
查看次数

标签 统计

boost-python ×2

python ×2

c++ ×1