编程语言
首页 > 编程语言> > Boost.python重载了numpy数组和python列表的构造函数

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

作者:互联网

给定使用Boost.Python公开的C类,如何公开两个构造函数:

>一个采用numpy数组,和
>另一个需要python列表?

解决方法:

我不是100%的意思,但我假设你想让一个构造函数采用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.

标签:boost-python,python
来源: https://codeday.me/bug/20190903/1797798.html