On Mar 19, 2008, at 4:23 AM, Francesco Guerrieri wrote: > Hi :) > I'm just beginning to experiment with Cython. It involves a slight (or > not-so-slight!) rethinking of some > approaches, but it seems rather smooth to me. I think that I like > it :) > Now I come to my question: I'm trying to understand how to manage > memory, > which is definitely something which you don't do in your python coding > of everyday :-) > > I am trying to dynamically size an array. > Could you link me to some example (the sage codebase will be fine) > or link? > > As I expected, > cdef int size = 10 > cdef int p[size] > > doesn't work. I found the following link > http://permalink.gmane.org/gmane.comp.python.cython.devel/162 > which seemed very promising :-) but I don't see any reply to it... > > I have found the following code in one of the Demos > (numeric_demo.pyx): > > cdef float *elems > elems = <float *>a.data > > but a.data (a is an Array) is not initialized in the example :) > > I have found the following page on the wiki > http://www.sagemath.org:9001/MallocReplacements > but doesn't answer my basic question. I _know_ am that I am missing > something very basic. > Ah, unfortunately I have no working knowledge of the C API, > while probably the answer lies there..
Have you ever written code in C? Cython, with respect to pointer memory management, is exactly the same. What you should do is include stdlib.pxi (inside the cython/includes directory). Alternatively, you can just paste that code at the top of your file. You now have 3 functions--request memory, resize memory, and free memory. A typical example would be cdef int size = 10 cdef float *elms = <float *>malloc(size * sizeof(float)) # returns a chunk of memory that's size * sizeof(float) bytes big [do some stuff with elms] size *= 2 cdef float *elms = <float *>realloc(elms, size * sizeof(float)) # makes your chunk bigger, possibly moving (and copying) the old data [some more stuff] free(*elms) # tell the system you no longer need this chunk of memory. If you don't do this, you will have a memory leak If you're putting this array in cdef classes, a good place to put malloc is in the __cinit__ (aka __new__) method, and put a free in the __dealloc__ method. That way you know whenever you request memory you will give it back when you're done. - Robert _______________________________________________ Cython-dev mailing list [email protected] http://codespeak.net/mailman/listinfo/cython-dev
