Python 的内存管理架构(Objects/obmalloc.c):
代码如下:
_____ ______ ______ ________
[ int ] [ dict ] [ list ] ... [ string ] Python core |
+3 | <----- Object-specific memory -----> | <-- Non-object memory --> |
_______________________________ | |
[ Python's object allocator ] | |
+2 | ####### Object memory ####### | <------ Internal buffers ------> |
______________________________________________________________ |
[ Python's raw memory allocator (PyMem_ API) ] |
+1 | <----- Python memory (under PyMem manager's control) ------> | |
__________________________________________________________________
[ Underlying general-purpose allocator (ex: C library malloc) ]
0 | <------ Virtual memory allocated for the python process -------> |
0. C语言库函数提供的接口
1. PyMem_*家族,是对 C中的 malloc、realloc和free 简单的封装,提供底层的控制接口。
2. PyObject_* 家族,高级的内存控制接口。
3. 对象类型相关的管理接口
PyMem_*
PyMem_家族:低级的内存分配接口(low-level memory allocation interfaces)
Python 对C中的 malloc、realloc和free 提供了简单的封装:
为什么要这么多次一举:
不同的C实现对于malloc(0)产生的结果有会所不同,而PyMem_MALLOC(0)会转成malloc(1). 不用的C实现的malloc与free混用会有潜在的问题。python提供封装可以避免这个问题。 Python提供了宏和函数,但是宏无法避免这个问题,故编写扩展是应避免使用宏源码:
Include/pymem.h#define PyMem_MALLOC(n) ((size_t)(n) > (size_t)PY_SSIZE_T_MAX ? NULL / : malloc((n) ? (n) : 1))#define PyMem_REALLOC(p, n) ((size_t)(n) > (size_t)PY_SSIZE_T_MAX ? NULL / : realloc((p), (n) ? (n) : 1))#define PyMem_FREE free Objects/object.c/* Python's malloc wrappers (see pymem.h) */void *PyMem_Malloc(size_t nbytes){ return PyMem_MALLOC(nbytes);}...
新闻热点
疑难解答