Py_BuildValue, Array from C to Python

Hi all,
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?
Any help is appreciated, kind regards Philipp

On Fri, Jan 16, 2009 at 2:34 PM, Philipp Heuser <philipp@achtziger.de> wrote:
Hi all,
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?
Create an empty list (PyList_New(0)) and then append (PyList_Append) items (PyFloat_FromDouble) as you loop over this array variable. I'm considering for some reason you don't know the size of this variable, so it has a sentinel in the end, but if it is not the case you can create a list with its final size and then use PyList_SetItem.
Any help is appreciated, kind regards Philipp
-- -- Guilherme H. Polo Goncalves

On Fri, Jan 16, 2009 at 8:34 AM, Philipp Heuser <philipp@achtziger.de> wrote:
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?
Try creating a Python tuple or list in your C function and returning that object instead. You can read about those C API functions here:
http://docs.python.org/c-api/tuple.html http://docs.python.org/c-api/list.html
-- Jon Parise (jon of indelible.org) :: "Scientia potentia est"

Philipp Heuser <philipp@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) { Py_DECREF(lst); return NULL; } PyList_SET_ITEM(lst, i, num); // reference to num stolen } return lst;
participants (4)
-
Guilherme Polo
-
Hrvoje Niksic
-
Jon Parise
-
Philipp Heuser