On 12/27/08, Robert Kern <robert.k...@gmail.com> wrote: > Daniel Fetchinson wrote: > >> I agree that array.array is more efficient than a list but the input >> for my function will come from PIL and PIL returns a list. So I have a >> list to begin with which will be passed to the C function. > > With recent versions of PIL, numpy can create an array from an Image very > quickly, possibly without any copying of memory. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it > had > an underlying truth." > -- Umberto Eco > > -- > http://mail.python.org/mailman/listinfo/python-list >
Hi Robert, now that we are at it let me ask something related. Now I managed to get my lists to C, operate on them in C and convert the result back to a python tuple. Since this is my first C program that uses the python C API I'm sure there are refcounting issues that I'm not considering, maybe also memory management too. 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; } Do I have to free the memory occupied by the python objects list1 and list2? Do I have to do any refcounting for list1, list2, tuple? Any comment on the above code will be very appreciated! If I'm pushed in the right direction I'm a fast learner but the beginning steps are always hard :) Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown -- http://mail.python.org/mailman/listinfo/python-list