Skip to content

Instantly share code, notes, and snippets.

@JonathanRaiman
Created December 16, 2014 06:10
Show Gist options
  • Save JonathanRaiman/deb1d82a2c6b00bbfe84 to your computer and use it in GitHub Desktop.
Save JonathanRaiman/deb1d82a2c6b00bbfe84 to your computer and use it in GitHub Desktop.
Little trivial example of memory allocation and deallocation in cython with arrays, points, structs, and more...
from libc.stdlib cimport malloc, free, realloc
cdef struct Chair:
int size
cdef class Bench:
cdef Chair* chairs
cdef readonly int num_chairs
property chairs:
def __get__(self):
ret = []
for i in range(self.num_chairs):
ret.append(self.chairs[i].size)
return ret
def __cinit__(self):
pass
def add_some_chairs(self, int n):
cdef Chair* chairs = <Chair *>malloc(n * sizeof(Chair))
cdef int i = 0
for i in range(n):
chairs[i] = Chair(i)
cdef int ret_type = self.add_chairs(chairs, n)
free(chairs)
if ret_type == 2:
raise MemoryError("Could not allocate chairs")
cdef int add_chairs(self, Chair[] chairs, int num_chairs) nogil:
cdef int i, j
cdef Chair * mem
if num_chairs == 0:
mem = <Chair * >malloc(num_chairs * sizeof(Chair))
if mem != NULL:
self.chairs = mem
for i in range(num_chairs):
self.chairs[i] = chairs[i]
return 1
else:
return 2
else:
mem = <Chair * >realloc(self.chairs, (self.num_chairs + num_chairs) * sizeof(Chair))
if mem != NULL:
self.chairs = mem
j = 0
for i in range(self.num_chairs, self.num_chairs + num_chairs):
self.chairs[i] = chairs[j]
j += 1
self.num_chairs = self.num_chairs + num_chairs
return 1
else:
return 2
def __dealloc__(self):
free(self.chairs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment