Boost.python overloaded constructor for numpy arra

2019-05-15 23:42发布

问题:

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.