[Cython] Automatic conversion with fixed-size C arrays

Stefan Behnel stefan_ml at behnel.de
Sat Oct 25 19:07:23 CEST 2014


Kurt Smith schrieb am 16.07.2014 um 19:01:
> Being able to convert between simple C structs and Python dictionaries is
> great, but it doesn't work if there is a fixed-size array field in the
> struct.  It seems like the following struct should be convertible safely:
> 
> cdef struct state_t:
>     int i, j, k
>     float x[3]
>     float v[3]
> 
> Along with that, I'd expect that converting between fixed-sized C arrays
> and Python iterables should work as well:
> 
> def auto_convert(list ll):
>     cdef int arr[10] = ll
>     # ...
>     return arr

I implemented this, it's in master.

There were multiple places in the code where array assignments were either
blocked or special cased (or not special cased yet), so many that I'm sure
I missed some. Please give it a try and report any problems.

I also had to dig through some custom type conversion code and convert it
from C to Cython to make it support more complex type conversions
automatically.

What should work now is:

- assigning C arrays by value (which came more as a side effect)
- copying Python iterables to C arrays on assignment (also recursively)
- coercing C arrays to Python lists (and tuples if you cast)

Pull requests that add more tests are *very* welcome. See
carray_coercion.pyx for stuff that works and e_ass.pyx for some error tests.

Stefan



More information about the cython-devel mailing list