Extending python

Lyle Johnson ljohnson at resgen.com
Wed May 23 13:21:07 EDT 2001

>     Are there any docs which provide examples on how to extend python with
> C/C++ other than the one at www.python.org??  I don't seem to understand
> to use PyObject *.  If I pass a list or tuple to my C function, and in my
> function I extract the list or tuple using "O" as a format specifier in a
> call to PyArg_ParseTuple, how do I actually get the integers or strings
> the PyObject???  What I'm trying to do is pass a variable number of data
> my C function through an array.  So is it proper to pass a list/tuple to
> C wrapper function and extract the elements into a dynamic array, which I
> then pass to my C function?  Please advise...

If you have a pointer to a PyObject, and you know that the object is a
"sequence" of some kind (including Python lists and tuples), you can extract
the objects in that sequence using PySequence_GetItem(), e.g.

    PyObject* sequenceObj;
    PyObject* sequenceItem;
    int i, size;

    if (!PySequence_Check(sequenceObj)) {
        fprintf(stderr, "You filthy liar! This isn't a sequence!\n");

    size = PySequence_Size(sequenceObj);
    if (size == -1) {
        /* An error occurred... */

    for (i = 0; i < size; i++) {
        sequenceItem = PySequence_GetItem(sequenceObj, i);
        if (sequenceItem == NULL) {
            /* an error occurred */
        else {
            /* do something with this sequence element */

There are also APIs to deal directly with Python list and tuple objects
(PyList_Size, PyList_GetItem, PyTuple_Size and PyTuple_GetItem) but you
provide yourself with a lot more flexibility by using the abstract
"sequence" APIs.

Hope this helps,


More information about the Python-list mailing list