python - 使用 boost::python 将虚拟成员函数从 C++ 公开到 Python

标签 python c++ boost boost-python

我尝试向 python 公开两个不同的类,但无法编译它。我尝试遵循 boost::python 示例,效果很好。但是,如果我尝试为我的类编写包装类,它就不起作用。我在下面提供了两个最小的示例:

struct Base
{
    virtual ~Base() {}
    virtual std::unique_ptr<std::string> f() = 0;
};

struct BaseWrap : Base, python::wrapper<Base>
{
    std::unique_ptr<std::string> f()
    {
        return this->get_override("f")();
    }
};

struct Base
{
    virtual ~Base() {}
    virtual void f() = 0;
};

struct BaseWrap : Base, python::wrapper<Base>
{
    void f()
    {
        return this->get_override("f")();
    }
};

第一个示例由于唯一指针而无法编译(我认为 boost::python 不使用唯一指针?),第二个示例提示 void 函数内的 return 语句。有人可以帮我解决这个问题吗?

最佳答案

这些示例无法编译,因为:

  • 第一个示例尝试将未指定的类型( override::operator() 的返回类型)转换为不兼容的类型。特别是,Boost.Python 目前不支持 std::unique_ptr ,因此不会转换为它。
  • 当调用函数声明返回void时,第二个示例尝试返回上面提到的未指定类型。 .

从 Python 的角度来看,字符串是不可变的,尝试将字符串的所有权从 Python 转移到 C++ 违反了语义。但是,可以在 C++ 中创建字符串的拷贝,并将复制字符串的所有权传递给 C++。例如:

std::unique_ptr<std::string> BaseWrap::f()
{
  // This could throw if the Python method throws or the Python
  // method returns a value that is not convertible to std::string.
  std::string result = this->get_override("f")();

  // Adapt the result to the return type.
  return std::unique_ptr<std::string>(new std::string(result));
}

this->get_override("f")() 返回的对象具有未指定的类型,但可用于转换为 C++ 类型。如果 Python 抛出异常,则覆盖的调用也会抛出异常;如果从 Python 返回的对象不可转换为 C++ 类型,则转换为 C++ 类型也会抛出异常。


这是一个完整的示例 demonstrating将返回的 Python 对象适配为 C++ 对象的两种方法。如上所述,override可以使用转换。或者,可以使用 boost::python::extract<> ,允许在执行转换之前检查转换是否会失败:

#include <memory> // std::unique_ptr
#include <boost/algorithm/string.hpp> // boost::to_upper_copy
#include <boost/python.hpp>

struct base
{
  virtual ~base() {}
  virtual std::unique_ptr<std::string> perform() = 0;
};

struct base_wrap : base, boost::python::wrapper<base>
{
  std::unique_ptr<std::string> perform()
  {
    namespace python = boost::python;
    // This could throw if the Python method throws or the Python
    // method returns a value that is not convertible to std::string.
    std::string result = this->get_override("perform")();

    // Alternatively, an extract could be used to defer extracting the
    // result.
    python::object method(this->get_override("perform"));
    python::extract<std::string> extractor(method());

    // Check that extractor contains a std::string without throwing.
    assert(extractor.check());

    // extractor() would throw if it did not contain a std::string.
    assert(result == extractor());

    // Adapt the result to the return type.
    return std::unique_ptr<std::string>(new std::string(result));
  }
};

BOOST_PYTHON_MODULE(example)
{
  namespace python = boost::python;
  python::class_<base_wrap, boost::noncopyable>("Base", python::init<>())
    .def("perform", python::pure_virtual(&base::perform))
    ;

  python::def("make_upper", +[](base* object) {
    auto result = object->perform(); // Force dispatch through base_wrap.
    assert(result);
    return boost::to_upper_copy(*result);
  });
}

交互式使用:

>>> import example
>>> class Derived(example.Base):
...     def perform(self):
...         return "abc"
...        
>>> derived = Derived()
>>> assert("ABC" == example.make_upper(derived))

关于python - 使用 boost::python 将虚拟成员函数从 C++ 公开到 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33476774/

相关文章:

python - Django 模型中的自定义 id 字段

c++ - 什么 API 会启动 FTP 传输并向 GUI 报告状态?

c++ - Boost 1.59 链接器错误

c++ - boost 信号双倍免费?

Python Pandas为选定列的逐行最大值添加列

python - Python 中的 Kruskal 算法

带有 ØÆÅ 字母的 Python 正则表达式

c++ - 使用 Boost 解析 XML 属性

c++ - 限制 CPU 速度以进行分析

c++ - 用 boost::function 定义 boost 信号?