PyList_SetItem的第三个参数是要添加到列表中的Python对象,通常从C类型转换,如下例所示:
/* This adds one to each item in a list. For example:
alist = [1,2,3,4,5]
RefArgs.MyFunc(alist)
*/
static PyObject * MyFunc(PyObject *self, PyObject *args)
{
PyObject * ArgList;
int i;
PyArg_ParseTuple(args, "O!", &PyList_Type, &ArgList));
for (i = 0; i < PyList_Size(ArgList); i++)
{
PyObject * PyValue;
long iValue;
PyValue = PyList_GetItem(ArgList, i);
/* Add 1 to each item in the list (trivial, I know) */
iValue = PyLong_AsLong(PyValue) + 1;
/* SETTING THE ITEM */
iRetn = PyList_SetItem(ArgList, i, PyLong_FromLong(iValue));
if (iRetn == -1) Py_RETURN_FALSE;
}
Py_RETURN_TRUE;
}PyObject_SetItem与此类似。区别在于PyList_SetItem窃取了引用,但PyObject_SetItem仅借用它。 PyObject_SetItem不能与不可变对象一起使用,如元组。