cythoncythonize

How does one get a pointer to a Cython memoryview's data?


With the new Cython 3.0+ API, the usage of ndarray.data within Cython code is deprecated.

My question is how does one obtain a pointer to the underlying ndarray data then that is held by a memoryview? What is the proper syntax or methodology that abides by the NPY_1_7 C-API and Cython's new 3.0+ API?

My code used to look something like this:

arr = np.zeros((10,))

# arr_data is a pointer to the underlying data
cdef double* arr_data = <double*>arr.data

# I want a pointer because it can be passed efficiently to other functions
do_something_to_arr_data_in_cythonorcpp(arr_data)


cdef do_something_to_arr_data_in_cythonorcpp(double* arr_data):
    for idx in range(10):
        arr_data[idx] += idx

Solution

  • That's easy, just take the address of the first element of the memory view:

    cdef int[::1] mm_view_1 = np.arange(100)
    cdef int* p_int_1 = &mm_view_1[0]
    
    cdef int[:, ::1] mm_view_2 = np.arange(100).reshape(10, 10)
    cdef int* p_int_2 = &mm_view_2[0][0]
    

    The step 1 in the memoryview int[::1], int[:, ::1] makes sure the underlying array is continuous in memory on corresponding dim.

    You can get more information in the doc https://cython.readthedocs.io/en/latest/src/userguide/memoryviews.html#pass-data-from-a-c-function-via-pointer