C API: array of floats/ints from python to C and back

Daniel Fetchinson fetchinson at googlemail.com
Sat Dec 27 22:47:08 EST 2008


>> This is the function I have, the corresponding python function will
>> take two equal length lists of integers and the C function will
>> compute their sum and return the result as a python tuple.
>>
>>
>> static PyObject *func( PyObject * self, PyObject * args )
>> {
>>     int j, N;
>>     int * src1, * src2;
>>     PyObject *list1, *list2;
>>
>>     list1 = PyTuple_GetItem( args, 0 );
>>     N = PyList_Size( list1 );
>>     src1 = ( int * ) malloc( N * sizeof( int ) );
>>     for( j = 0; j < N; j++ )
>>     {
>>         src1[j] = (int)PyInt_AsLong( PyList_GetItem( list1, j ) );
>>     }
>>
>>     list2 = PyTuple_GetItem( args, 1 );
>>     N = PyList_Size( list2 );
>>     src2 = ( int * ) malloc( N * sizeof( int ) );
>>     for( j = 0; j < N; j++ )
>>     {
>>         src2[j] = (int)PyInt_AsLong( PyList_GetItem( list2, j ) );
>>     }
>>
>>     PyObject * tuple;
>>     tuple = PyTuple_New( N );
>>     for( j = 0; j < N; j++ )
>>     {
>>         PyTuple_SetItem( tuple, j, PyInt_FromLong( (long)( src1[j] +
>> src2[j] ) ) );
>>     }
>>
>>     free( src1 );
>>     free( src2 );
>>
>>     return tuple;
>> }
>
> 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.

Daniel

-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown



More information about the Python-list mailing list