[capi-sig] Py_BuildValue, Array from C to Python

Hrvoje Niksic hniksic at xemacs.org
Sun Jan 18 09:56:05 CET 2009

Philipp Heuser <philipp at achtziger.de> writes:

> I am trying to return an array from C to Python. Since it is of
> variable size,
> return Py_BuildValue("[f,f,f]", array[0], array[1], array[2]);
> does not help. How do I do that?

You can do it like you'd do it in Python: get an empty list, append
array elements to it in a loop, and return the resulting list when
you're done.  Since you're coding it in C, it might make sense to
attempt to be a bit more efficient and preallocate the list to exactly
the needed size.

PyObject *lst = PyList_New(array_len);
if (!lst)
    return NULL;
for (i = 0; i < array_len; i++) {
    PyObject *num = PyFloat_FromDouble(array[i]);
    if (!num) {
        return NULL;
    PyList_SET_ITEM(lst, i, num);   // reference to num stolen
return lst;

More information about the capi-sig mailing list