Christopher Barker | 5 Oct 20:24 2009
Picon

Re: Passing Lists of Objects from Python to C


Robert Bradshaw wrote:
> On Oct 5, 2009, at 10:13 AM, Mikhail Veygman wrote:
>>
>> C function I can write myself so it can vary.

Then write it in Cython...

> A bit verbose, but that's because you need to malloc/free explicitly, so 
> it's difficult to know the "right" way to automatically convert a list 
> to an int*.

Or use numpy -- it has all sorts of nifty code for converting sequences 
of python types to numpy arrays, which use a C pointer to store the 
data, so it does all that work for you. You can then work with the numpy 
array directly in python or Cython, or grab the pointer and pass that 
off to C.

Something like this:

import numpy as np
cimport numpy as np

def foo_int(L):
     # L should be a sequence of objects that can be turned into ints
     cdef np.ndarray[np.int_t, ndim=1]
     arr = np.array(L, dtype=np.int)

     # now you have a numpy array which you can work with directly
     cdef int i
     for i in range(arr.size):
         do_something_with(arr[i])

Or you can grab the pointer, if you really want to pass it to C, but 
I'll leave that as an exercise for the reader ;-)

Here is a good place to start:

http://wiki.cython.org/tutorials/numpy

I'd probably make use of numpy in your Python code anyway -- so maybe 
you wouldn't have the lists to begin with!

If you really don't want the numpy dependency, you may be able to use 
the std array.array class instead for this simple case.

-Chris

--

-- 
Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker <at> noaa.gov


Gmane