[Cython] [cython-users] Re: callback function pointer problem

mark florisson markflorisson88 at gmail.com
Fri Sep 30 21:34:40 CEST 2011

On 29 September 2011 22:48, Robert Bradshaw
<robertwb at math.washington.edu> wrote:
> On Thu, Sep 29, 2011 at 5:29 AM, mark florisson
> <markflorisson88 at gmail.com> wrote:
>> On 29 September 2011 13:13, Miguel Angel <skuda21 at gmail.com> wrote:
>>>> Structs already coerce to python dicts. In the memoryview branch it
>>>> also does the reverse, i.e. coerce a dict to a struct (you have to be
>>>> careful with strings, making sure you hold a reference to the string
>>>> object as long as you use the pointer in the struct). You have to be
>>>> sure to declare every struct attribute though.
>>> Could i see an example usage of this in any repository or the documentation? I
>>> can't find any.
>>> Regards,
>>> Miguel Angel.
>> It's not in the documentation yet, I updated that in a branch that
>> still needs to be merged (which hopefully will be in 0.16). The
>> functionality from struct -> object is there though:
>> cdef extern from *:
>>    ctypedef struct MyStruct:
>>        int attrib
>> cdef MyStruct s = {'attrib':10} # Note, this is NOT object->struct
>> conversion, it only eats compile-time expressions here
> or even
>    s = MyStruct(attrib=10)

That looks very nice, a lot more intuitive than the dict assignment.

> It would be natural to support array -> list conversion for slices the
> baseclass is convertable, e.g.
>    cdef double* data = ...
>    print data[:10]
> Converting an int[10] to a Python object without slicing is a bit odd as
>    cdef int a[10]
>    [compute a]
>    cdef object o = a
>    a[0] = something else
>    o[1] = another thing
> is non-initiative, as arrays can't be assigned in C and "assignment"
> of lists in Python are by reference, not by copy. "o = a[:]" is plenty
> clear that there's a copy, so that's better. The other way is a bit
> messier, but
>    a[:n] = [python list]
> could certainly be supported via an implicit loop. Another
> consideration is that with primitive data types we're venturing into
> memory view territory, which might be a more useful representation
> than Python lists.
> - Robert

Indeed. Currently you can only cast pointers to memoryview slices, but
there's no reason to not support arrays as well (without also needing
to first cast the array to a pointer). So if arrays have shape
information, you could immediately coerce to memoryview (cython.array)
objects without needing a cast. This would also work for arrays in
structs, as they can only ever have a static size (known at C compile

Shall we support that? I won't be hard as the infrastructure for
casting pointers is already there.

More information about the cython-devel mailing list