C API: array of floats/ints from python to C and back

Robert Kern robert.kern at gmail.com
Sun Dec 28 03:39:47 CET 2008


Daniel Fetchinson wrote:
>>> I agree that array.array is more efficient than a list but the input
>>> for my function will come from PIL and PIL returns a list. So I have a
>>> list to begin with which will be passed to the C function.
>> With recent versions of PIL, numpy can create an array from an Image very
>> quickly, possibly without any copying of memory.
> 
> What exactly do you mean? (1) PIL creates a list which can be easily
> converted by numpy to a numpy.array or (2) with the help of numpy one
> can create a numpy.array from an image directly?

(2) a = numpy.asarray(img)

> Since I will have to pass the list or numy.array to C anyway I don't
> see any advantage to (1) although (2) can be useful.

(1) is still somewhat useful, if you're willing to bear the cost of the numpy 
dependency. The conversion code from any Python sequence to a numpy array of the 
desired type and dimensionality is a 2-liner (function call and error check). 
The memory is managed by numpy, so all you have to do is manage the refcount of 
the array object like any other Python object.

Okay, 5-liner given C's verbosity:

     intx = PyArray_FROM_OTF(pyintx, PyArray_INT, NPY_IN_ARRAY);
     if (!intx) {
         PyErr_SetString(PyExc_ValueError, "intx must be an array of ints");
         goto fail;
     }

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list