Dear all,
we have created a new package
https://pypi.org/project/memory-allocator/ (refactored from a SageMath module). It is just a little extension class, which allocates memory for you and frees all the memory when deallocated. Usage:
from memory_allocator cimport MemoryAllocator
cdef int foo():
cdef MemoryAllocator mem = MemoryAllocator()
cdef int* foo = <int*> mem.allocarray(100, sizeof(int))
return foo[53]
cdef class MyClass:
cdef MemoryAllocator mem
cdef int* foo
def __cinit__(self):
self.mem = MemoryAllocator()
self.foo = <int*> self.mem.calloc(100, sizeof(int))
It spares you from writing a custom `__dealloc__` function or from freeing memory at every possible point of exit of a function. `MemoryAllocator` has a small overhead in comparison to `libc.stdlib`: The above function takes about 40ns for me, in contrast to only 9ns that it would take with plain `malloc`/`free`.
For me, this overhead is usually worth it and spares me from code duplication and prevents errors.
Jonathan Kliem