From 2388e9327892a438440b522ff5c43d817458ed99 Mon Sep 17 00:00:00 2001 From: Stefan Behnel Date: Fri, 11 Oct 2013 18:02:45 +0200 Subject: [PATCH] mention PyMem_*() C-API functions in memory allocation tutorial --- docs/src/tutorial/memory_allocation.rst | 34 ++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/docs/src/tutorial/memory_allocation.rst b/docs/src/tutorial/memory_allocation.rst index 94ed130..c0df674 100644 --- a/docs/src/tutorial/memory_allocation.rst +++ b/docs/src/tutorial/memory_allocation.rst @@ -45,16 +45,36 @@ A very simple example of malloc usage is the following:: # return the previously allocated memory to the system free(my_array) -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. +Note that the C-API functions for allocating memory on the Python heap +are generally preferred over the low-level C functions above as the +memory they provide is actually accounted for in Python's internal +memory management system. They also have special optimisations for +smaller memory blocks, which speeds up their allocation by avoiding +costly operating system calls. + +The C-API functions can be found in the ``cpython.mem`` standard +declarations file:: + + from cpython.mem cimport PyMem_Malloc, PyMem_Realloc, PyMem_Free + +Their interface and usage is identical to that of the corresponding +low-level C functions. + +One important thing to remember is that blocks of memory obtained with +:c:func:`malloc` or :c:func:`PyMem_Malloc` *must* be manually released +with a corresponding call to :c:func:`free` or :c:func:`PyMem_Free` +when they are no longer used (and *must* always use the matching +type of free function). Otherwise, they won't be reclaimed until the +python process exits. This is called a memory leak. + If a chuck of memory needs a larger lifetime then can be managed by a -``try..finally`` block, another helpful idiom is to tie its lifetime to a -Python object to leverage the Python runtime's memory management, e.g.:: +``try..finally`` block, another helpful idiom is to tie its lifetime +to a Python object to leverage the Python runtime's memory management, +e.g.:: cdef class SomeMemory: - cdef doube* data + cdef double* data def __init__(self, number): # allocate some memory (filled with random data) @@ -75,4 +95,4 @@ Python object to leverage the Python runtime's memory management, e.g.:: It should be noted that Cython has special support for (multi-dimensional) arrays of simple types via NumPy and memory views which are more full featured and easier to work with than pointers while still retaining the speed/static -typing benefits. \ No newline at end of file +typing benefits. -- 2.7.4