[C++-sig] wrapping vector of pointers

Jim Bosch talljimbo at gmail.com
Tue Jan 26 20:56:30 CET 2010


On Tue, 2010-01-26 at 13:36 +0100, martin manduch wrote:
> 
> I want to make XVec responsible for memory, which is addressed through
> pointers, but I don't know how.
> 

That would be difficult, especially because you can't really subclass
std::vector in a safe way.

> 
> I need to wrap vector of pointers, because it's parameter in one function...
> 

If it's only used in one function, I'd recommend writing a custom
wrapper for that function that does a manual conversion from a Python
list.  Something like this:

void py_accept_vector(boost::python::list const & sequence) {
    int size = boost::python::len(sequence);
    std::vector<X*> vector(size);
    for (int n = 0; n < size; ++n) {
        boost::python::extract<X*> converter(sequence[n]);
        if (!converter) {
            PyErr_SetString(
                PyExc_TypeError, 
                "Expected sequence of 'X' objects."
            );
	    boost::python::throw_error_already_set();
        }
        vector[n] = converter();
    }
    accept_vector(vector); // The passed vector's items are managed
                           // by Python, and cannot be relied upon
                           // to be valid after the function exits.
}

You can then wrap "py_accept_vector" in the usual way:

boost::python::def("accept_vector", py_accept_vector);

Hope that helps!


Jim Bosch



More information about the Cplusplus-sig mailing list