Robert Bradshaw wrote: > 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) )
Actually, no: a.strides is what amounts to a size_t* since a is typed to ndarray. A long-standing usability problem. So, check a.strides[0] == n*sizeof(float), a.strides[1] == sizeof(float). The usual way is to check a.flags['C_CONTIGUOUS'], although this tends to be a bit too conservative sometimes (arrays which are contiguous are not flagged as such; that's a problem with NumPy). -- Dag Sverre _______________________________________________ Cython-dev mailing list [email protected] http://codespeak.net/mailman/listinfo/cython-dev
