C API: array of floats/ints from python to C and back
Daniel Fetchinson
fetchinson at googlemail.com
Sun Dec 28 02:44:29 EST 2008
>>> As others already said, using a Numpy array or an array.array object
>>> would
>>> be more efficient (and even easier - the C code gets a pointer to an
>>> array
>>> of integers, as usual).
>>
>> I looked for this in the C API docs but couldn't find anything on how
>> to make an array.array python object appear as a pointer to integers
>> (or floats, etc) in C code. On
>>
>> http://docs.python.org/c-api/concrete.html#sequence-objects
>>
>> There is only list and tuple or maybe you mean byte array? That has
>> only been introduced in python 2.6 and I'm working on 2.5.
>
> array is a library module, and isn't really part of the API. You're
> looking for the buffer protocol:
> PyObject_AsReadBuffer/PyObject_AsWriteBuffer; see
> http://docs.python.org/c-api/objbuffer.html
>
> Given an array.array('l') (containing C long integers):
>
> int do_something(PyObject* obj)
> {
> long *vec;
> Py_ssize_t nbytes, nitems, i;
>
> if (PyObject_AsReadBuffer(obj, (const void **)&vec, &nbytes) != 0)
> return NULL;
> nitems = nbytes/sizeof(long);
> for (i=0; i<nitems; i++) {
> /* do something with vec[i] */
> }
> return ret;
> }
>
> From Python you can get "vec" and "nitems" using the buffer_info() method
> of array objects.
Thanks very much, this was very helpful!
Cheers,
Daniel
--
Psss, psss, put it down! - http://www.cafepress.com/putitdown
More information about the Python-list
mailing list