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?
解决方案
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 CreateWithList(list lst)
{
// construct with a list here
}
shared_ptr CreateWithPyArrayObject(PyArrayObject* obj)
{
// construct with numpy array here
}
BOOST_PYTHON_MODULE(mymodule)
{
class_ >
("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.