JMzance JMzance - 3 months ago 8
Python Question

Converting a numpy array into a c++ native vector

I currently have a python C extension which takes a PyObject list and I can parse is using 'PySequence_Fast'.

Is there an equivalent command which would allow my to parse a one dimensional numpy array?

Cheers,
Jack

Answer

The function PyArray_FROM_OTF converts to a numpy array (unless the argument is already a numpy array when it just returns it with an incremented refcount). See http://docs.scipy.org/doc/numpy/user/c-info.how-to-extend.html#converting-an-arbitrary-sequence-object. e.g.

PyObject* definitely_numpy_array = PyArray_FROM_OTF(might_be_numpy_array,
                 NPY_DOUBLE, // you need to specify a type
                 0 // there's assorted flags you can add to describe the exact format you want which are described in the documentation
                 )

This can work on any number of dimensions so if you strictly require 1D you'll have to add a check. It also requires the numpy headers to be included ("numpy/arrayobject.h")