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.

share|improve this question
up vote 2 down vote accepted

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.

share|improve this answer
    
What is the equivalent function for PyLong_FromLong if I want to add a C object (Atom) to the list? – user2117235 Mar 12 '13 at 14:35

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.