passing large arrays from C to Python as arguments

Benjamin Tai bt98 at doc.ic.ac.uk
Sun Jun 2 06:03:50 EDT 2002


Chris Fonnesbeck wrote:

> I am looking for a way of passing relatively large arrays to python as
> an argument to a method call, without hard-coding the length of the
> array using Py_BuildValue. Is there an obvious solution to this, like
> passing it in a dictionary, or something? At any rate, it is very
> awkward to have to pass each element of each array into the argument
> individually.
>
> Thanks,
> cjf

Hi,

Not too sure if the suggestion would work out for you: implementing an
extension function which return a list to Python. If so, please read on.

Assuming you have an array "a" of length "size":



PyObject* p_list_ret;

 p_list_ret = PyList_New(size); assert(p_list_ret!=NULL);

 for (ix=0; ix<size; ix++)
     PyList_SetItem(p_list_ret, ix, PyLong_FromLong(a[ix]));

 return p_list_ret;



Be careful with the borrow reference issue in the PyList_SetItem(). You
might find it helpful to look at the API document first.


Thanks

Ben




More information about the Python-list mailing list