[Pyrex] access to c data class members
Daniele Varrazzo
daniele.varrazzo at gmail.com
Sun Aug 27 20:51:44 UTC 2006
ahalda at cs.mcgill.ca wrote:
> Hi,
>
> I am having trouble accessing c-data in a pyrex class. My class has a pointer
> to some c data (in a struct). It looks like some people have recently
> mentioned similar problems on the list, but I wasn't clear on the answer.
>
> The goal is to have a non-member function modify the data and return a
> (new) python object. The tricky thing is that the data does not map to a
> python type. (It works otherwise)
>
> EG:
> ------------------------------------
> cdef class MyClass:
> cdef OBJSTRUCT *data #pointer to a struct
>
> def load_File():
> newObj = MyClass() #alternately, 'cdef Module newMod'
> newObj.data = c_mod.getData() #returns pointer to the new object
> return newObj
> ------------------------------------
You can declare newObj being of the exact class you expect:
def load_File():
cdef MyClass newObj
newObj = MyClass()
newObj.data = getData()
return newObj
so newObj is C-typed and you can access its C members.
Alternatively you can cast the python instance on the fly when you need
to access C members:
def load_File():
newObj = MyClass()
(<MyClass>newObj).data = getData()
return newObj
The first method involves a __Pyx_TypeTest call: if you try to set to
newObj anything different from a MyClass instance, a TypeError is
elegantly raised.
The second methods doesn't involve such check: it is faster when you are
_really_ sure your object is the instance you expect (as in your
example, unless MyClass has some funky metaclass). If you are not sure
(e.g. you are getting a Python object from outside) it is basically
asking for a core dump.
Disclaimer: this is what i learned reading the C code generated by
Pyrex: if there is a serious reason to avoid such code, i'd be glad to
know it.
Daniele
More information about the Pyrex
mailing list