extending with C

Alex Martelli aleax at aleax.it
Wed Jan 9 08:03:57 EST 2002


"Jesper Olsen" <jolsen at mailme.dk> wrote in message
news:cf0ad9fb.0201090453.206772a2 at posting.google.com...
> I need to write a python extension in C, and the method interface should
> be able to handle "arrays of float".
>
> In the python code, the array could be represented as a tupel, a list or
> an array it is not really important.

Then have it be an array (with typecode 'f') on the Python side, as
it makes the rest extremely easy.


> The extension needs to be able to receive such arrays, and to return them
> to python.
>
> How to do this? The python documentation only documents how to do this
> for simpel types.

Methods .tostring and .fromstring of array objects (documented in the
Python documentation) make "simple type" objects (specifically strings)
from array objects and vice versa.  Method buffer_info gives you the
numeric address and number of items in the array, you might prefer to
use that to access the array's internals.


> One way I can imagine is to use the "O" format string with
PyArg_ParseTuple,
> and get back a pointer to the python object, which could be manipulated
> through the python C-Api.

Yes, that's right - and what you do with the C API is call tostring on
the array object you receive.


> Is there a better way of doing this?

Some would choose to use Numpy arrays instead.  However, Numpy is a
separate (and largish) package, while module array is part of any
Python distribution, so, unless there's something else arrayish that
you need to do, I don't think Numpy is "better" in this context.

> In java this kind of interface is well documented through the jarray
types...

And in Python through the array module.


Alex






More information about the Python-list mailing list