[C++-sig] automatic conversion of tuple to vector

Jim Bosch talljimbo at gmail.com
Tue May 25 01:04:07 CEST 2010

On 05/24/2010 03:00 PM, Nathan Cournia wrote:
> Basically, the desired behavior is to have a C++ function which
> accepts a vector in C++; accept a tuple/list when in Python.
> I'm not sure if the FAQ is up-to-date.  Is this still not possible in
> boost.python?  How do people generally get the behavior I outlined
> above?

In general, you'll have to write your own custom wrapper that takes a 
boost::python::object argument, and wrap that, to get this behavior:

void py_foo(boost::python::object const & py_array) {
     std::vector<int> array;
     // <copy py_array into array>
     // <copy array back into py_array>

boost::python::def("foo", &py_foo);

The copies are unavoidable if your C++ function takes a container, 
rather than a templated iterator range, simply because your Python 
object doesn't actually contain a std::vector.  If you can work with an 
iterator range, check out my from_python_iterator class, part of the 
Python extensions in the boost sandbox:


Along with the to-python iterator found in the main Boost.Python 
distribution, it should also help in the case where you have to make copies.


Jim Bosch

More information about the Cplusplus-sig mailing list