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

Aaron Brady castironpi at gmail.com
Sun Dec 28 01:40:39 CET 2008

On Dec 27, 6:06 pm, Scott David Daniels <Scott.Dani... at Acm.Org> wrote:
> Daniel Fetchinson wrote:
> >.... I have a list to begin with which will be passed to the C function.
>  > I assume converting the list to an array.array and passing that to the C
> > function doesn't make any difference in terms of speed since the
> > operation itself will be done in the C function anyway.
> Right, but why bother to do the conversion in C where you'll have to
> fiddle with refcounts and error propogation?  convert in python, and
> go to the underlying data in C.

I think you could use ctypes.c_int* 20, which is an awesome data
type-- a 20-element array of integers.  You could also use this, which
I just discovered, and is actually moderately disturbing.

#WARNING unsafe code
>>> from ctypes import *
>>> i= c_int(42)
>>> pi= pointer(i)
>>> pi[0]
>>> pi[1]
>>> pi[2]
>>> pi[1]= 20
>>> pi
<__main__.LP_c_long object at 0x00A97D00>
>>> pi[1]

What memory is it overwriting?

More information about the Python-list mailing list