c++ - 如何在 Boost::Python 中向 C++ 类型添加自定义隐式转换?

标签 c++ python boost-python

在我的 C++ 代码中,我有一个 Foo 类,其中包含许多将 Bar 类型变量作为参数的方法:

class Foo {
public:
  void do_this(Bar b);
  void do_that(Bar b);
  /* ... */
};

Bar 有许多构造函数,可以从许多常见类型(如 int、std::string、float 等)创建新对象:

class Bar {
public:
  Bar(int i);
  Bar(float f);
  Bar(std::string s);
  /* ... */
};

我用 Boost::Python 包装了它,现在我可以直接使用 Python 文字调用我的 Foo 方法,因为它们被隐式转换为 Bar 对象。

f = Foo()
f.do_this(5)
f.do_that("hello")

现在,我还希望能够使用其他 Python 类型,例如元组,如下所示:

f.do_that((1,2,3))

但我不想触及原始的 Bar 定义,也不想用 Boost::Python 的东西污染我的 C++ 库。我想在我的绑定(bind)代码中编写一个包装函数,但我不明白这是否可能以及这样做的正确方法是什么。

换句话说:我可以注册一个工厂函数以用作 Python 中的自动转换吗?

最佳答案

在包装器代码附近对 Bar 进行子类化,并为您的子类提供一个接受 bp::object(或更具体的 python 类型)的构造函数

struct Bar_wrapper:Bar,bp::wrapper<Bar>
{
    Bar_wrapper(bp::object arg)
    {
        //code to build a Bar_wrapper Here
    }
}

然后将一个Bar_wrapper 导出到python 而不是一个Bar,并将其称为Bar 作为python 名称:

class<Bar_wrapper>("Bar")
    ...
    .def(init<bp::object>())
    ...

关于c++ - 如何在 Boost::Python 中向 C++ 类型添加自定义隐式转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1254013/

相关文章:

python - 在 Python 中填充 CSV 中的空点

c++ - 将python脚本添加到c++项目

c++ - 使用 libtar 压缩目录

c++ - 使用 () 的 POD 成员类型的构造函数初始化列表

c++ - 为什么 string::replace 在 C++11 中不指定分配器的异常?

c++ - boost .python : Argument types did not match C++ signature

c++ - boost::python 函数调用中 boost::shared_ptr 的转换

c++ - 使用算法中的插入函数在空容器中插入元素未给出预期结果

python - 使用loop.create_task创建的asyncio事件循环任务是否为FIFO

python - 输出列表中负数的索引(使用结构递归)