【问题标题】:build error while exposing classes to python using boost.python使用 boost.python 向 python 公开类时生成错误
【发布时间】:2013-06-26 05:11:46
【问题描述】:

我在使用 Boost.Python 库向 python 公开抽象类时遇到了一些问题。我正在使用 1_53_0 boost 和 Python 33。

有一个与此问题相关的类似线程。 (How can I implement a C++ class in Python, to be called by C++?) 我在关注eudoxos 的响应,他在其中对抽象类 Base 进行了封装,该类具有返回字符串类型的方法。

我正在做类似的事情,但我经常收到编译错误:

  • 错误 1 ​​错误 C2668: 'std::basic_string<_elem>::basic_string' : 对重载函数 d:\temp\example\example.h 的模糊调用 20
  • 8 IntelliSense:从“boost::python::detail::method_result”到“std::string”的不止一个用户定义转换适用:d:\temp\example\example.h 20

以上错误与该行有关:

return this->get_override("getName")();

如下图所示:

#include <string>
#include "boost/python.hpp"

class Person {

public:

    virtual std::string getName() { return "Base"; };

    virtual void setName(std::string name) {};

};

class PersonWrap : public Person, public boost::python::wrapper<Person>
{

public:

    std::string getName()
    {
        return this->get_override("getName")();
    }

    void setName(std::string name)
    {
        this->get_override("setName")();
    }
};

class Student : public Person {

public:

    std::string getName() { return myName; };

    void setName(std::string name) { myName = name; };

    std::string myName;
};

BOOST_PYTHON_MODULE(example)
{
    boost::python::class_<PersonWrap, boost::noncopyable>("Person")
        .def("getName", (&Person::getName))
        .def("setName", (&Person::setName))
    ;

    boost::python::class_<Student, boost::python::bases<Person>>("Student")
        .def("getName", (&Student::getName))
        .def("setName", (&Student::setName))
    ;
}

感谢任何cmets,在此先感谢!

【问题讨论】:

  • 如果Person 是纯虚拟的,为什么getName() = 0setName(...) = 0 不在他们的声明中?您是否在其他地方提供实现?如果是这样,用boost::python::pure_virtual 包裹&amp;Person::getName 是否正确?
  • 感谢您的评论,我没有意识到代码与我的问题不符。但是,它仍然没有解决我最初的问题。

标签: c++ python boost-python


【解决方案1】:

我找到了解决这个问题的方法,它的工作原理是这样的:

std::string getName()
{
    //return this->get_override("getName")();
    return boost::python::call<std::string>(this->get_override("getName")());
}

但是,根据the boost python documentation,这只能用于 MSVC6/7,这不是我的情况,因为我使用的是 VS2010 (MSVC 10.0)。

【讨论】:

    猜你喜欢
    • 2017-07-04
    • 1970-01-01
    • 1970-01-01
    • 2013-07-26
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    • 2014-08-25
    • 1970-01-01
    相关资源
    最近更新 更多