[Cython] how to allow access to data in a C array?
Stefan Behnel
stefan_ml at behnel.de
Thu Jul 2 06:32:43 CEST 2009
Hi,
Chris Colbert wrote:
> I'm thinking this may be what the new array type is for, but i'm not sure.
>
> say I have a C struct which I wrap as a class:
>
>
> #mycfile.h
> struct Foo
> {
> int* data[32];
> };
>
> #my_dec_file.pxd
> cdef exter from "mycfile.h":
>
> cdef struct Foo:
> int* data[32]
>
> #my_cy_file.pxd
> cimport my_dec_file
>
> cdef class Foo:
> cdef my_dec_file.Foo* thisptr
>
> #my_cy_file.pyx
> cimport my_dec_file
>
> cdef class Foo:
> property data:
> def _get_(self):
> return self.thisptr.data <----i dont think this will work
Right, it won't.
> what I want to be able to do in python is this:
>
> <....get an instance of Foo i.e. foo = Foo() ....>
>
> b = foo.data[3:6] # where b can be a numpy array or a list, but a
> numpy array would be better
>
> Further, is there a way to manipulate data like that directly via
> python (i.e. without making a copy).
>
> suppose I want to add the value 2 to every value in foo.data[:]
>
> it would be nice to do (from python):
>
> foo.data[:] + 2
>
> Is there a way to implement that on the Cython side?
Sure, just return an object from the "data" property that wraps the array
and implements __setitem__ and __getitem__ appropriately. Not exactly
trivial, but not too hard either.
Once Cython has better array support, I guess this would simply become a
builtin feature.
Stefan
More information about the Cython-dev
mailing list