Py_BuildValue - return large array

Michael P. Reilly arcege at shore.net
Sat May 6 09:01:47 EDT 2000


j vickroy <jvickroy at sec.noaa.gov> wrote:
: Hello all,

: How should one return a (handle to?) "large" C-array to Python?

: It seems that Py_BuildValue ("[...]", ..., ...) is only usable for
: "small" arrays where one can explicitly enumerate each element in the
: array.

: Thanks for your time.

You probably don't want to use Py_BuildValue().  For one, if you have a
large array, then you might have problems enumerating the values in the
function call (as seperate arguments).

I would suggest creating a Python list object explicitly and populating
it that way.  For example,

PyObject *Convert_Big_Array(long array[], int length)
  { PyObject *pylist, *item;
    int i;
    pylist = PyList_New(length);
    for (i=0; i<length; i++) {
      item = PyInt_FromLong(array[i]);
      PyList_SetItem(pylist, i, item);
    }
    return pylist;
  }

If you had an array that took different data types, than you could have
code to create Python objects of different types.

You also mentioned passing a "handle" (pointer?) to a C array.  You
can either create a new Python type to wrap the array around (using
SWIG, or writing your own type), or you can use the PyCObject type:

  {
    PyObject *pyarray;
    pyarray = PyCObject_FromVoidPtr(array, NULL);
    return pyarray;
  }

You might also want to look into the NumPy module, but that might be
overkill for you. :)

I hope this helps you,
  -Arcege




More information about the Python-list mailing list