Dynamic memory allocation is mostly a non-issue in Python. The simplest example is that of lists, which can grow to any required size.
Lists can be used in Cython, but they can only hold Python objects which incurs a certain amount of overhead. For C data types, this must be dealt with in a similar way to the usual C language: namely by using malloc, realloc and, importantly, free.
One can get a feeling for this need by studying the example contained in primes.pyx: the return array has a fixed, maximum length, which is hard coded in the script. This length cannot be changed at run time, to change it one has to recompile.
To gain access to these function is very easy: just use "cimport libc.stdlib" (see the Cython/Includes/ directory).
A very simple example of malloc usage is the following:
1 import random 2 from libc.stdlib cimport malloc, free 3 4 def random_noise(int number=1): 5 cdef int i 6 cdef double *my_array = <double *>malloc(number * sizeof(double)) 7 if not my_array: 8 raise MemoryError() 9 10 try: 11 ran = random.normalvariate 12 for i in range(number): 13 my_array[i] = ran(0,1) 14 15 L = [ my_array[i] for i in range(number) ] 16 finally: 17 # whatever happens, make sure we do not leak memory 18 free(my_array) 19 20 return L
One important thing to remember is that blocks of memory obtained with malloc must be manually released with free when one is done with them or it won't be reclaimed until the python process exits. This is called a memory leak.
The .pxd file actually defines the relevant functions like so:
1 # standard cimport file libc/stdlib.pxd 2 3 cdef extern from "stdlib.h": 4 void free(void* ptr) 5 void* malloc(size_t size) 6 void* realloc(void* ptr, size_t size) 7 # ...
This declares the required functions as provided by the C standard library.