Python:ctypes 和垃圾回收

Python: ctypes and garbage collection

我有以下代码片段 代码说明了具有动态分配的矩阵(二维数组)

C

int** create_matrix(int r, int c)
{
    int i, j, count;

    int **arr = (int **)malloc(r * sizeof(int *));
    for (i=0; i<r; i++)
        arr[i] = (int *)malloc(c * sizeof(int));


    count = 0;
    for (i = 0; i <  r; i++)
       for (j = 0; j < c; j++)
          arr[i][j] = ++count;  

    return arr;
}

Python(调用 C 函数)

r = 3
c = 3
p_int = POINTER(POINTER(c_int))
testlib.create_matrix.restype = POINTER(POINTER(c_int))
p_int = testlib.create_matrix(r, c) #does p_int and inner array deallocated automatically in python?

我的问题是:

  1. python/ctypes 是否处理 C 分配的内存的取消分配?
  2. 如果我们要求它手动取消分配,那怎么办?免费电话还是其他?
    • 任何博客或 post 阐明相同的内容都很棒

Does python/ctypes handles de-allocation of memory allocated by C?

如果您的代码调用 malloc();您有责任调用调用 free().

的代码

If we require it to de-allocate manually then how? Calling free or something else? any blog or post which clarifies same would be great

C 代码应提供互补的 free_matrix() 函数,该函数应由调用 create_matrix() 的代码调用。 free_matrix()example.

有很多实现

您可以将 create_matrix()free_matrix() 包装到一个对象中,然后在其 __del__() 方法中调用 free_matrix()。 And/or 如果你想要更确定的方法(调用时间 __del__() 或者是否调用它取决于实现);你可以创建一个上下文管理器:

from contextlib import contexmanager

@contextmanager
def matrix():
    m = Matrix() # calls create_matrix() internally
    try:
        yield m # Matrix() may protect against out-of-bound error
    finally:
        m.clear() # call free_matrix()

示例:

with matrix() as m:
   print(m[0][1])