Re: [cython-users] pointer to memory view

1,952 views
Skip to first unread message

Stefan Behnel

unread,
May 17, 2013, 4:19:37 AM5/17/13
to cython...@googlegroups.com
Kevin Kunzmann, 03.05.2013 16:28:
> I have a pointer to some data and the dimensions of the array (and the size
> of the data type), what would be the best way of constructing a memory view
> from that? I only found explanations for the other direction.

There is a NumPy C-API function in numpy.pxd that wraps a memory block in
an array, without copying the data.

If this is not what you want, please provide more details about your use
case. Do you really want a memory view or a NumPy array object? I.e., what
do you want to do with it afterwards?

Stefan

Stefan Behnel

unread,
May 17, 2013, 4:20:32 AM5/17/13
to cython...@googlegroups.com
Kevin Kunzmann, 17.05.2013 09:45:
> cdef int i = 0
> for i from 0 <= i < n_samples:

Note that this is better spelled

cdef int i
for i in range(n_samples):
...

Stefan

Josh Ayers

unread,
May 18, 2013, 2:51:39 AM5/18/13
to cython...@googlegroups.com, stef...@behnel.de
On Friday, May 17, 2013 2:02:42 AM UTC-7, Kevin Kunzmann wrote:
I think I got it working,

cimport cython

import numpy as np
cimport numpy as np
np.import_array()

ctypedef np.float64_t DOUBLE_t

def g():
    cdef np.ndarray[DOUBLE_t, ndim=1] A = np.arange(10, dtype=np.float64)
    cdef DOUBLE_t* a = <DOUBLE_t*> A.data
    cdef np.ndarray[DOUBLE_t, ndim=1] B = np.PyArray_SimpleNewFromData(1, [10], np.NPY_FLOAT64, a)
    return B.copy()

My only problem now is that I have to give the type as np.NPY_FLOAT64 explicitely, I tried a ctypedef np.NPY_FLOAT64 C_DOUBLE_t, but that did not work, how do I solve that properly?

The np.NPY_FLOAT64 and similar constants are just integer codes that are meant to be passed to the various NumPy array creation functions.  The actual types are np.float64_t, float32_t, etc.

If you just want a memoryview to use within Cython, this should work without copying the data.  I'm assuming X_ptr is the 2D C array, with the elements stored row-first, and its size is nrows by ncols.

from numpy cimport float64_t
cdef Py_ssize_t nrows = xxx, ncols = xxx
cdef float64_t [:, ::1] X = <float64_t [:nrows, :ncols]> X_ptr

Note that the memoryview won't free the memory of the underlying C array.  You'll have to do that yourself once you're done with it.

Hope that helps.
 

Sturla Molden

unread,
May 18, 2013, 8:26:22 AM5/18/13
to cython...@googlegroups.com, cython...@googlegroups.com, stef...@behnel.de
Den 18. mai 2013 kl. 08:51 skrev Josh Ayers <josh....@gmail.com>:

>
> from numpy cimport float64_t
> cdef Py_ssize_t nrows = xxx, ncols = xxx
> cdef float64_t [:, ::1] X = <float64_t [:nrows, :ncols]> X_ptr
>

Yes, that is the way to do it.

Just forget about np.ndarray[whatever], it is not a memory view. :)


Sturla



Reply all
Reply to author
Forward
0 new messages