3

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?
0

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. This looks great! Where is PyArrayObject defined? (I am using MacPorts and have installed py27-numpy, but that doesn't seem to expose any headers with PyArrayObject. I looked for dev variants, but couldn't find any.)
Also, is there a way to do this without the boost::shared_ptr? Or else, is there a way to wrap my other static member functions that return MyClass so that they return shared_ptr?
I got this working with shared_ptr! However, I still can't find any header with PyArrayObject. I will just ask another question. Thanks again for your detailed help.
@NeilG: The numpy api is all defined in <numpy/arrayobject.h>.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.