[Pyrex] cdef'd classes initialization
Lenard Lindstrom
len-l at telus.net
Tue Aug 8 19:29:41 UTC 2006
On 8 Aug 2006 at 18:33, Daniele Varrazzo wrote:
> Hello,
>
> i wrote some Pyrex classes to wrap C structures. Usually such classes
> are responsible for the wrapped structure, and properly allocate them on
> the heap and initialize on __init__ and free on __dealloc__. This is the
> normal behaviour for all the instances directly created by a Python program.
>
First, it is better to use __new__ instead of __init__ for C members.
> Inside Pyrex, i don't always want such behavior. For example i have some
> composite structures: the component is accessed from the composing
> structure using a property. When the property __get__ is invoked, i
> create from Pyrex a new instance to wrap the component structure. But
> this instance doesn't own the wrapped structure: on __dealloc__ it must
> not free() anything.
>
You can use a root class for the case of no allocation/deallocation,
and a derived class to export to Python. Here is an example. It also
shows how to access C members/methods from a factory function.
cdef class CRoot:
"""For factory function"""
cdef int datum
def get_datum(self):
return self.datum
def make_object(int datum):
cdef CRoot o
o = CRoot()
o.datum = datum
return o
cdef class C(CRoot):
"""Has allocator/deallocator"""
def __new__(self, int datum):
self.datum = datum
def __dealloc__(self):
pass
Lenard Lindstrom
<len-l at telus.net>
More information about the Pyrex
mailing list