Boost.python overloaded constructor for numpy array and python list

天涯浪子 提交于 2019-12-22 10:22:54

问题


Given a C++ class exposed with Boost.Python, how do I expose two constructors:

  • one that takes a numpy array, and
  • another that takes a python list?

回答1:


I'm not a 100% on what you mean, but I'm assuming that you want to have a constructor taking a Python list and another one taking a numpy array. There are a couple of ways to go about this. The easiest way is by using the make_constructor function and overloading it:

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))
}

You can be even more clever and use an arbitrary type/number of arguments in your constructor. This requires a bit of voodoo to accomplish. See http://wiki.python.org/moin/boost.python/HowTo#A.22Raw.22_constructor for a way to expose a raw function definition as a constructor.



来源:https://stackoverflow.com/questions/5713795/boost-python-overloaded-constructor-for-numpy-array-and-python-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!