[Pyrex] Access to nested structures and arrays
Pierre GM
pgmdevlist at gmail.com
Mon Mar 19 12:24:18 UTC 2007
On Friday 16 March 2007 16:19:29 Robert Bradshaw wrote:
> > First question:
> > When writing extension types, am I limited to use only Python
> > objects as
> > arguments of __init__ ?
>
> Yes, as __init__ cannot be a cdef function (otherwise it wouldn't be
> callable via python).
OK, duely noted.
> > Third question:
> > how can I modify the underlying C array from Python ?
>
> You can't. You have to write a python function that when called
> modifies the array.
Well, I realized that I don't really need a numpy array for that, a simple
list should do the trick as I have a limited number of elements. So I wrote a
small extension:
cdef class modelflags:
cdef int *c_list[8]
cdef object str_list
def __new__(self):
cdef int i
self.str_list = [False] * 8
def __getitem__(self, idx):
return self.str_list[i]
def __setitem__(self, idx, val):
cdef int tmpval
tmpval = val
self.c_list[i] = &tmpval
self.str_list[i] = bool(val)
def __str__(self):
return self.str_list
The idea was to overload the __setitem__, so that I could modify the
underlying C array directly.
Elsewhere in the code, I initalize the pyrex extension type wrapped around one
of the substructures, with a tailor-made setup function
cdef setup(self, c_struct *base, long npar):
...
self.parametric_flags = modelflags()
self.parametric_flags.c_list[0] = base.parametric[0]
where c_struct is the underlying C structure declared in a .pxd
That compiles OK, but the Python code sends me a
AttributeError: 'modelflags' object has no attribute c_list.
when the setup function gets called.
My understanding was that c_list, even if private, could still be accessed by
the pyrex code. Obviously I'm missing something here, but could you tell me
what ?
> Perhaps if you think of things in terms of providing a python
> interface to manipulating the underlying c structure, rather than
> trying to expose the c structure itself, things would become easier
> to do.
Er, yes, but I have no idea how. The rest of the external code uses this
nested structure as the key object, using some substructures for inputs, some
others for outputs, and calling the structure at once for some
initialization. I tried to get rid of the initialization part and cinstruct
the structure from my extnsion types, but that doesn't work either... At
least, with the current version I tried to describe you, I'm able to convert
the C outputs back to python, converts most of the inputs from python to C,
but for this particular array that needs to be read/write.
Thanks again for your time
More information about the Pyrex
mailing list