[C++-sig] Arrays to python

Ng, Enrico enrico.ng at lmco.com
Thu Jan 21 15:10:41 CET 2010

That was just my example, I do not require it to go into a numeric array.  It just seemed like the way I was suppose to do it based on the documentation.  As long as I can access the data in any form in python, I'll be happy.  And I only need to read the data, I do not need to modify the array.

I did see your library but I was hoping to be able to do this without incorporating another library. 

I had hoped that there was something simple after seeing the numeric part in the documentation.

Enrico Ng

-----Original Message-----
From: Jim Bosch [mailto:talljimbo at gmail.com] 
Sent: Wednesday, January 20, 2010 8:03 PM
To: cplusplus-sig at python.org
Cc: Ng, Enrico
Subject: Re: [C++-sig] Arrays to python

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:


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


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


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