Creating a cython memoryview manually

53 views Asked by At

I have a contiguous 1-d numpy array that holds data. However, this array is really a buffer, and I have several numpy views to access that data. These views have different shapes, ndims, offsets etc ...

For instance :

import numpy as np
import math as m

shape_0 =(2,3) 
shape_1 = (2,2,2)

shifts = np.zeros((3),dtype=np.intp)
shifts[1] = m.prod(shape_0)
shifts[2] = shifts[1] + m.prod(shape_1)

buf = np.random.random((shifts[2]))
arr_0 = buf[shifts[0]:shifts[1]].reshape(shape_0)
arr_1 = buf[shifts[1]:shifts[2]].reshape(shape_1)

print(buf)
print(arr_0)
print(arr_1)

My question is the following: How can I do the same thing, but in cython using memoryviews in a nogil environment ?

1

There are 1 answers

4
Sen On

You can mark a whole function (either a Cython function or an external function) as nogil by appending this to the function signature or by using the @cython.nogil decorator:

#python
@cython.nogil
@cython.cfunc
@cython.noexcept
def some_func() -> None:
...
#cython
cdef void some_func() noexcept nogil:
....

You can use context managers:

with nogil:
    #dosomething

https://cython.readthedocs.io/en/latest/src/userguide/nogil.html https://cython.readthedocs.io/en/latest/src/tutorial/numpy.html