On Mar 29, 2009, at 9:45 PM, Tiago Pereira wrote: > David Cournapeau wrote: >> >> float *dest; >> for i in range(nrows): >> mempcy(dest + i * ncols, a[i], number of bytes in a[i]) >> >> and then use dest to create a numpy array. > > Thanks guys for all your help! I've managed to get it working. I > now use > the following functions to convert from float ** to 2D numpy and > vice-versa: > > cdef inline float **npy2c_float(np.ndarray a): > cdef int m = a.shape[0] > cdef int n = a.shape[1] > cdef int i > cdef float **data > data = <float **> malloc(m*sizeof(float*)) > for i in range(m): > data[i] = &(<float *>a.data)[i*n] > return data > > cdef inline np.ndarray c2npy_float(float **a, int n, int m): > cdef np.ndarray[DTYPE_t,ndim=2]result = np.zeros > ((m,n),dtype=DTYPE) > cdef float *dest > cdef int i > dest = <float *> malloc(m*n*sizeof(float*)) > for i in range(m): > memcpy(dest + i*n,a[i],m*sizeof(float*)) > free(a[i]) > memcpy(result.data,dest,m*n*sizeof(float*)) > free(dest) > free(a) > return result > > This of course assumes a is contiguous.
BTW, you can make sure the array is contiguous by checking that a.strides == ( n*sizeof(float), sizeof(float) ) >> In C, using ragged arrays is generally not a good idea - of >> course, if >> your externaly library uses it, you have no choice, but for your own >> code, you are often better using plain float*. > > I see. And it seems that float* is also more flexible for n-d arrays. > But, another dumb C question, if you have an array as float*, can you > use it (in C) as array[i][j] or you need to refer to it as array[i > +ncols*j]? No, you can't do array[i][j] because C wouldn't have a way of getting ncols. float** is literally an list of pointers. > Thanks again for all the help and for making the great piece of > software > that Cython is! On behalf of the many people who've contributed, you're welcome. Glad you're finding it as useful as we have :) - Robert _______________________________________________ Cython-dev mailing list [email protected] http://codespeak.net/mailman/listinfo/cython-dev
