How to check whether a memmoryview in Null in cython

1k Views Asked by At

I want to check whether a memory view is initialized with None. I have a function like this:

cdef void test(int[:] a):
    if a == NULL:
        print("invalid data")

cdef int[:] memview = None
test(memview)

I get this error when I compile this:

Invalid types for '==' (int[:], void *)

Is the problem assigning None to the memmory view? If that's not the case, what can I do to detect the NULL values?

Thanks!

1

There are 1 best solutions below

4
DavidW On

Turning my comments into a very answer:

You are assigning None to your memoryview:

cdef int[:] memview = None

Therefore it makes sense to check it against None, not against NULL:

if a is None:

Ultimately they're similar concepts but different things: NULL is a pointer that doesn't point to anything, while None is a singleton Python object that indicates that something is unset. The distinction is really between C level and Python level and here memoryviews act "Python level".


There's an additional detail that lets you do if a is None inside a nogil block: Python ensures that there is exactly one None object in existence (and also that it remains the same None object for the entire program). Therefore it's possible to translate a is None to the C code

((PyObject *) __pyx_v_a.memview) == Py_None

i.e. a simple pointer comparison, that doesn't need the GIL since there's no changes to reference counts.