【发布时间】:2015-02-27 08:11:51
【问题描述】:
我有以下代码 sn-ps 代码说明了动态分配的矩阵(二维数组)
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?
我的问题是:
- python/ctypes 是否处理 C 分配的内存的取消分配?
- 如果我们要求它手动取消分配,那该怎么办?打电话免费还是别的?
- 任何阐明相同内容的博客或帖子都会很棒
【问题讨论】:
-
为什么会有
p_int = POINTER(POINTER(c_int))这一行?这并没有做任何有用的事情。 -
ctypes 不会
free指针数组,也不会是行。首先,它不拥有内存,所以这将是一个糟糕的主意。再加上它不知道p_int指向一个指针数组,也不知道数组的长度,那么它怎么知道它需要免费调用r+1次呢?