Boost.python 重载numpy数组和python列表的构造函数

3 投票
1 回答
2050 浏览
提问于 2025-04-16 16:01

假设你有一个用Boost.Python暴露的C++类,你想让这个类有两个构造函数:

  • 一个是接收一个numpy数组的,
  • 另一个是接收一个Python列表的。

1 个回答

5

我不太确定你具体想表达什么,但我猜你的意思是想要一个构造函数,可以接收一个Python列表,还有一个可以接收numpy数组的构造函数。实现这个有几种方法。最简单的方法是使用make_constructor函数,并对其进行重载:

using boost;
using boost::python;

shared_ptr<MyClass> CreateWithList(list lst)
{
    // construct with a list here
}

shared_ptr<MyClass> CreateWithPyArrayObject(PyArrayObject* obj)
{
    // construct with numpy array here
}


BOOST_PYTHON_MODULE(mymodule)
{
    class_<MyClass, boost::noncopyable, boost::shared_ptr<MyClass> >
        ("MyClass", no_init)
        .def("__init__", make_constructor(&CreateWithList))
        .def("__init__", make_constructor(&CreateWithPyArrayObject))
}

你甚至可以更聪明一点,在构造函数中使用任意类型和数量的参数。这需要一些特别的技巧来实现。可以查看这个链接 http://wiki.python.org/moin/boost.python/HowTo#A.22Raw.22_constructor,了解如何将一个原始函数定义作为构造函数来使用。

撰写回答