Manage calls to calloc/free through Cython
Maintained. Last release 5 weeks ago, commits in 2 of the last 26 weeks. Weaker on commit activity and release cadence.
pip install cymemcymem: A Cython Memory Helper
cymem provides two small memory-management helpers for Cython. They make it easy to tie memory to a Python object's life-cycle, so that the memory is freed when the object is garbage collected.
Overview
The most useful is cymem.Pool, which acts as a thin wrapper around the calloc
function:
from cymem.cymem cimport Pool
cdef Pool mem = Pool()
data1 = <int*>mem.alloc(10, sizeof(int))
data2 = <float*>mem.alloc(12, sizeof(float))
The Pool object saves the memory addresses internally, and frees them when the
object is garbage collected. Typically you'll attach the Pool to some cdef'd
class. This is particularly handy for deeply nested structs, which have
complicated initialization functions. Just pass the Pool object into the
initializer, and you don't have to worry about freeing your struct at all — all
of the calls to Pool.alloc will be automatically freed when the Pool
expires.
Installation
Installation is via pip, and requires
Cython. Before installing, make sure that your pip,
setuptools and wheel are up to date.
pip install -U pip setuptools wheel
pip install cymem
Example Use Case: An array of structs
Let's say we want a sequence of sparse matrices. We need fast access, and a Python list isn't performing well enough. So, we want a C-array or C++ vector, which means we need the sparse matrix to be a C-level struct — it can't be a Python class. We can write this easily enough in Cython: