Search code examples
pythoncpython-embedding

Add C object to Python List & return the list of C objects to python


I am writing C extensions for python.

I want to know how to add a C object to python list using PyList_SetItem. For example,

I have a C object.

Atom *a = (Atom *)(PyTuple_GET_ITEM(tmp2, 0));

I made a list:

PyObject* MyList = PyList_New(3);

I am not sure what the third argument must be in the following statement.

PyObject_SetItem(MyList, 0, a);

Also how do I return this list of C objects to python.


Solution

  • The third argument to PyList_SetItem is the Python Object to be added to the list, which is usually converted from a C type, as in this simple example:

    /* 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 is similar. The difference is that PyList_SetItem steals the reference, but PyObject_SetItem only borrows it. PyObject_SetItem cannot be used with an immutable object, like a tuple.