[C++-sig] Arrays to python

Jim Bosch talljimbo at gmail.com
Thu Jan 21 02:02:45 CET 2010


On Wed, 2010-01-20 at 17:51 -0500, Ng, Enrico wrote:
> I have C code similar to the following:
> 
> float image_data[IMAGE_SIZE];
> const float *get_data()
> 
> get_data returns a pointer to image_data.  I'd like to expose get_data to python and have it return a copy of the array in some Python type.  (it is actually a 2D array of image data)
> 

I have to admit I'm not really familiar with using
boost::python::numeric; I don't know how well it works with numeric and
numarray's successor, numpy, and I pretty much use numpy exclusively (no
one is supporting the other two anymore).

But you can do this by using the numpy C API directly:

http://docs.scipy.org/doc/numpy/reference/c-api.array.html#from-scratch

and you can wrap the PyObject* you get back in a boost::python::object
like so:

#include <numpy/arrayobject.h>

boost::python::object py_get_data() {
    npy_intp shape[1] = { IMAGE_SIZE };    
    npy_intp strides[1] = { 1 };
    boost::python::handle<> array(
        PyArray_New(&PyArray_Type, 1, shape, NPY_FLOAT, strides,
                    get_data(), sizeof(float), NPY_C_ARRAY_RO, NULL)
    );  // handle is a C++ smart pointer for PyObject*
    return boost::python::object(array);
}

It's not elegant, but it should work.  It should even handle exceptions
in PyArray_New properly.  But you also have to do some work in the
module init function (in other words, inside the BOOST_PYTHON_MODULE
macro):

http://docs.scipy.org/doc/numpy/reference/c-api.array.html#importing-the-api

As a bit of self-promotion, I should mention I've written a fairly
extensive C++ multidimensional array library that provides automatic
boost::python converters to numpy, and might do what you're looking for
better:

http://code.google.com/p/ndarray/

Documentation for the Python stuff isn't great, but I'd be happy to
answer any questions.


Jim Bosch





More information about the Cplusplus-sig mailing list