returning Python Lists from C++

Michael P. Reilly arcege at shore.net
Wed Jul 7 12:07:04 EDT 1999


Mark Butterworth <mark.butterworth at cis.co.uk> wrote:
: Can anyone give me a quick example of how to return a python list object
: from a C++ function?

There are two ways,  Py_BuildValue and building your own PyListObject
yourself.

Using Py_BuildValue:
  return Py_BuildValue("[si]", "Spam, eggs and spam", 42);

The square brankets tell the function to build a python list and return
it with the contents; in this case a two element list with a Python string
and a Python integer.

Read about Py_BuildValue in section 1.9 of the "Extending and Embedding
the Python Interpreter" manual (http://www.python.org/doc/current/ext/
buildValue.html).

Making PyListObject objects:
  PyObject *list;

  list = PyList_New(2);
  PyList_SetItem(list, 0, PyString_FromString("Spam, eggs and spam"));
  PyList_SetItem(list, 1, PyInt_FromLong(42));
  return list;

Notice that I did not change the reference counts.  We are returning a
new list object, so we do not increment the reference count.  Also,
the SetItem function does not increment the reference count of the
elements, which are new objects anyway.

You can read about these in section 7.2.3 "List Objects" of the
"Python/C API Reference Manual" (http://www.python.org/doc/current/api/
listObjects.html).

  -Arcege





More information about the Python-list mailing list