using lists in C-extensions?

Jason Orendorff jason at jorendorff.com
Sat Feb 16 10:12:55 EST 2002


Marcus Stojek wrote:
> But I am still far too slow. So I have to go for C.
> My problem is, that I have to pass a list (or actually
> a couple of lists) to the C routine and after performing
> the calculations, returning them to Python.

It might be a good idea to use Numeric, and
pass a Numeric array into your function.

It will be nice and fast, since the data is stored as
a flat array.  (Otherwise, you get to trawl all over
memory to get the numbers out of that list of tuples.)

> As far as I understand things, I have to use
> PyArg_Parse() and Py_BuildValue() for this, right?

You probably only need PyArg_ParseTuple().
  http://www.python.org/doc/current/ext/parseTuple.html

You're right, there's no format for lists.
You want "O" or "O!".

  PyObject *myArray;

  if (!PyArg_ParseTuple(args, "O", &myArray))
      /* error, bad arguments */ ...
  if (!PyArray_Check(myArray))
      /* error, wrong type */ ...
  ...

If you really want to use a list of tuples, something
similar will work.

The ArrayObject C API is covered in Chapter 13 of
the NumPy manual:
  [PDF] http://www.pfdubois.com/numpy/numpy.pdf
The documentation seems kind of thin to me, but
basically you care about:
  PyArray_ContiguousFromObject(...)  // get contiguous data
  myArray->data          // the actual data
  PyArray_Size(myArray)  // how much of it there is
  myArray->descr->type   // what type it is
As always, mind your INCREFs and DECREFs.

And though you may already know all this, Alex Martelli's
sample code really helped me to pull it all together.
If this is your first C extension, take a look.
  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66509

## Jason Orendorff    http://www.jorendorff.com/




More information about the Python-list mailing list