Py_BuildValue - return large array

Christian Tismer tismer at tismer.com
Sat May 6 10:16:28 EDT 2000


Howdy,

thanks for your good advice.
But I suggest to never leave the error checking
code, since that teaches sloppy style to newcomers.
Added error checking:

"Michael P. Reilly" wrote:
> 
> 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;
>   }

Here the same routine, using an error check, plus
the (somewhat faster) PyList_SET_ITEM macro.

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

ciao - chris

-- 
Christian Tismer             :^)   <mailto:tismer at appliedbiometrics.com>
Applied Biometrics GmbH      :     Have a break! Take a ride on Python's
Kaunstr. 26                  :    *Starship* http://starship.python.net
14163 Berlin                 :     PGP key -> http://wwwkeys.pgp.net
PGP Fingerprint       E182 71C7 1A9D 66E9 9D15  D3CC D4D7 93E2 1FAE F6DF
     where do you want to jump today?   http://www.stackless.com




More information about the Python-list mailing list