I am currently using the new NUMPY_1_7 C API and Cython 0.29+. Usage of types like cnp.ndarray
are deprecated and it is preferred to use a Cython memoryview instead.
However, part of my code stores a ndarray of type 'object'. E.g.
cdef class A:
cdef cnp.ndarray buff
cdef void A_func(self):
self.buff = np.empty(10, dtype='object')
cdef int idx
for idx in range(10):
self.buff[idx] = CythonClass(5)
cdef void nogil_func(self) nogil:
cdef void** buff = <void**> self.buff
cdef int idx
for idx in range(10):
(< CythonClass > buff[idx]).do_something_nogil()
cdef class CythonClass:
def __cinit__(self, int n):
self.n = n
cdef int do_something_nogil(self) nogil:
cdef int result = 0
cdef int idx
for idx in range(5):
result += idx
return result
I have a few questions of how to covert the cdef cnp.ndarray buff
line into a Cython memoryview, such that it allows me to still leverage the data structure in nogil blocks:
- How would I go about converting
buff
into a Cython memorvyew that supports the storage of an "object"? Is the way below fine? - Are there alternatives?
- Are there tradeoffs to the alternatives in terms of speed and efficiency?
Here is my attempt:
cdef class A:
cdef object[:] buff
cdef void A_func(self):
self.buff = np.empty(10, dtype='object')
cdef int idx
for idx in range(10):
self.buff[idx] = CythonClass(5)
cdef void nogil_func(self) nogil:
cdef void** buff = <void**> self.buff
cdef int idx
for idx in range(10):
(<CythonClass> buff[idx]).do_something_nogil()
which results in the following error: operand of type '__Pyx_memviewslice' where arithmetic or pointer type is required