gpt4 book ai didi

Python:ctypes 和垃圾收集

转载 作者:太空宇宙 更新时间:2023-11-03 23:25:15 24 4
gpt4 key购买 nike

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

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. 如果我们要求它手动取消分配,那该怎么做?免费电话还是其他?
    • 任何阐明相同内容的博客或帖子都很棒

最佳答案

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() 方法。和/或如果您想要更确定的方法(调用 __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])

关于Python:ctypes 和垃圾收集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28760273/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com