Python lists ans sequence protocol from C API
Alex Martelli
aleaxit at yahoo.com
Wed Sep 22 17:47:11 EDT 2004
Matjaz <surfmatj at email.si> wrote:
...
> PySequence_SetItem with the following error message:
> "Unhandled exception at 0x1e04ed1a in python.exe:
> 0xC0000005: Access violation reading location 0x00000000."
> Could it be that basic lists do not support sequence protocol?
Once they're valid Python list objects, they do...
> Or am I missing something? I'm using Python 2.3.4 on Windows XP.
You're missing the fact that you're never building a valid Python list
object in your code. The slots, as PyObject*, are 'random', probably
null pointers. That's why you're supposed to use PyList_SET_ITEM
specifically to initialize these 'slots' WITHOUT trying to decref the
previously held item... there IS no 'previously held item'...!
> PyObject *argseq, *ov;
> int i, v, len;
>
> len = 2;
> argseq = PyList_New(len);
This does NOT initialize the slots of list argseq, as above explained.
> for (i=0; i<len; i++) {
> ov = PyInt_FromLong(i);
> printf("Index %d. Success %d.\n", i, PySequence_SetItem(argseq, i, ov));
> }
But this does try to decref that null pointer (or whatever), so, BOOM.
> Why would I wish to use sequence with basic lists protocol? Because my
> code should also deal with other sequence types, possibly subclassed from
> python lists.
Nevertheless they'll need to be properly built, inizialized, first.
Add initialization, such as an immediate:
for (i=0; i<len; i++) {
PyList_SET_ITEM(argseq, i, Py_BuildValue(""));
}
just after your
argseq = PyList_New(len);
and you should be fine with PySequence_whateveryouwish now.
Alex
More information about the Python-list
mailing list