我在学习C,同时也在尝试实现PythonC扩展,在我向它传递一个相当大的列表之前,这一切都是完美的。。。在
示例。。在
>>> import shuffle
>>> shuffle.riffle(range(100))
工作太好了!在
^{pr2}$
你知道我的问题是什么吗?在
#include <Python.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static PyObject *shuffle_riffle(PyObject *self, PyObject *args)
{
int const MAX_STREAK = 10;
int m, f, l, end_range, streak, *current_ptr;
double length;
PyObject * origList;
PyObject * shuffledList;
srand((int)time(NULL));
// parse args to list
if (! PyArg_ParseTuple( args, "O!", &PyList_Type, &origList) )
{
return NULL;
}
length = (int)PyList_Size(origList);
current_ptr = (rand() % 2) ? &f : &l;
end_range = (int)(length / 2) + (rand() % (length > 10 ? (int)(.1 * length) : 2));
shuffledList = PyList_New((int)length);
for(m = 0, f = 0, l = (end_range + 1), streak = 0; m < length && l < length && f < end_range + 1; m++, *current_ptr += 1)
{
double remaining = 1 - m / length;
double test = rand() / (double)RAND_MAX;
if (test < remaining || streak > MAX_STREAK)
{
current_ptr = (current_ptr == &f ? &l : &f);
streak = 0;
}
PyList_SetItem(shuffledList, m, PyList_GetItem(origList, *current_ptr));
streak += 1;
}
// change the pointer to the one that didn't cause the for to exit
current_ptr = (current_ptr == &f ? &l : &f);
while(m < length)
{
PyList_SetItem(shuffledList, m, PyList_GetItem(origList, *current_ptr));
m++;
*current_ptr += 1;
}
return Py_BuildValue("O", shuffledList);
}
static PyMethodDef ShuffleMethods[] = {
{"riffle", shuffle_riffle, METH_VARARGS, "Simulate a Riffle Shuffle on a List."},
{NULL, NULL, 0, NULL}
};
void initshuffle(void){
(void) Py_InitModule("shuffle", ShuffleMethods);
}
我发现你的代码有三个问题。在
首先,
PyList_GetItem
返回一个借用的引用,PyList_SetItem
窃取引用,这意味着您将得到指向同一对象的两个列表,但对象的引用计数将是1而不是2。这肯定会导致严重的问题(Python会在某个时候尝试删除已经删除的对象)。在第二,你没有检查错误。您应该检查所有Python调用的返回值,如果检测到问题,请减少您持有的所有引用并返回
NULL
。在例如:
然后,由于第一个问题,您必须在设置项时增加引用:
^{pr2}$您可以在这里使用
PyList_SET_ITEM
宏,因为您知道shuffledList
尚未初始化。在第三,这一行中泄漏了对
shuffledList
对象的引用:这相当于:
由于您已经拥有引用(因为您创建了此对象),所以您希望直接返回它:
泄漏引用意味着此列表永远不会从内存中释放。在
相关问题 更多 >
编程相关推荐