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

Daniel Fetchinson fetchinson at googlemail.com
Sat Dec 27 21:44:38 EST 2008


>>>> 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)

Thanks, I didn't know about this, maybe it will be useful.

>> 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;
>      }

Yes, the dependency on numpy is my main concern. If it will help with
my problem I don't mind the dependency actually, so I'll do more
detailed benchmarks first.

Thank you,
Daniel



-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown



More information about the Python-list mailing list