我的代码比较2个元组列表,如果第一个元组的所有元素都在第二个元组的范围内,则显示“ True”。范围由参数“ ar”设置。
#include <Python.h>
PyObject *compare( PyObject *self, PyObject *args )
{
PyObject *pList1;
PyObject *pList2;
PyObject *pItem1;
PyObject *pItem2;
Py_ssize_t n;
int i, i2;
int ar, ar2;
int c, s, b;
if (!PyArg_ParseTuple(args, "O!O!i", &PyList_Type, &pList1, &PyList_Type, &pList2, &ar)) {
PyErr_SetString(PyExc_TypeError, "parameter must be a list.");
return NULL;
}
ar2 = ar * 2;
n = PyList_Size(pList1);
for (i=0; i<n; i++) {
pItem1 = PyList_GetItem(pList1, i);
if(!PyTuple_Check(pItem1)) {
PyErr_SetString(PyExc_TypeError, "list items must be tuples.");
return NULL;
}
pItem2 = PyList_GetItem(pList2, i);
if(!PyTuple_Check(pItem2)) {
PyErr_SetString(PyExc_TypeError, "list items must be tuples.");
return NULL;
}
for (i2=0; i2<3; i2++) {
c = (int) PyInt_AsLong(PyTuple_GetItem(pItem1, i2));
s = (int) PyInt_AsLong(PyTuple_GetItem(pItem2, i2));
s -= ar;
b += ar2;
if(!(s <= c && c <= b)) {
return Py_False;
}
}
}
return Py_True;
}
在循环中进行了5000次迭代之后,Python退出了AppCrash。
答案 0 :(得分:0)
原因在参考计数器中。必须在返回Py_INCREF(Py_False)和Py_INCREF(Py_True)之前分别添加。