[Pyrex] How does pyrex manage memory that is malloced, realloced, etc.

len-l at telus.net len-l at telus.net
Mon Jun 27 02:50:10 CEST 2005


On 26 Jun 2005 at 15:19, Andreas Kostyrka wrote:

> Am Freitag, den 24.06.2005, 17:14 -0600 schrieb Nathaniel Haggard:
> > An extension that declares a pointer to a struct
> > 
> > cdef class A:
> >        struct1 *s
> > 
> > Also contains a method that wraps a C function that allocates memory.
> > 
> > def init_struc1:
> >       self.s = c_init()
> > 
> > Is the memory assigned to self.s safe from overwrites?  How does pyrex
> > handle the allocated memory?
> 
> Well, such as this
> 
> A().init_struct() 
> 
> would leak memory.
> 
> To demonstrate a correct way:
> 
> cdef class MyBuffer:
>     cdef char *buffer
> 
>     def __init__(self):
>         if self.buffer == NULL: # init can be called multiple times
>             self.buffer = malloc(128)
> 

The self.buffer = malloc(128) should be done in a __new__ method. This is called
only once when the object is actually created, so there is not need to check if
buffer is NULL first. It is where all internal C attributes should be initialised.
Method __new__  is explained in the "Special Methods of Extension Types" section 
of the the Pyrex doc.

One warning though. There was some talk of making the Pyrex __new__
more like a Python __new__, so code may have to be changed later before the
final release of Pyrex.

Lenard Lindstrom
<len-l at telus.net>




More information about the Pyrex mailing list