Passing a numpy pointer (dtype=np.bool) to C++ Passing a numpy pointer (dtype=np.bool) to C++ numpy numpy

Passing a numpy pointer (dtype=np.bool) to C++


It looks like the problem is with the array type declaration.According to the documentation at https://cython.readthedocs.org/en/latest/src/tutorial/numpy.html boolean arays aren't yet supported, but you can use them by casting them as arrays of unsigned eight bit integers.Here's a simple example that takes the sum of a 1D array of boolean values (the same as the sum() method would for a boolean NumPy array)

from numpy cimport ndarray as arcimport numpy as npcimport cython@cython.boundscheck(False)@cython.wraparound(False)def cysum(ar[np.uint8_t,cast=True] A):    cdef int i, n=A.size, tot=0    for i in xrange(n):        tot += A[i]    return tot

In your C++ code, depending on what you are doing, you may need to cast the pointer back to a bool, I'm not sure on that.

Edit: here's an example of how to cast the pointer in Cython, which should do what you want.I still had to type the array as an unsigned 8 bit integer, but I then cast the pointer back into a bool.

from numpy cimport ndarray as arcimport numpy as npfrom libcpp cimport boolcimport cythondef cysum(ar[np.uint8_t,cast=True] A):    cdef int i, n=A.size, tot=0    cdef bool *bptr    bptr = <bool*> &A[0]    for i in xrange(n):        tot += bptr[i]    return tot

If you want to pass the array in as a pointer, you could just use the following function in your Cython file:

cdef bool* arptr(np.uint8_t* uintptr):    cdef bool *bptr    bptr = <bool*> uintptr    return bptr

Which can be called as

arptr(&A[0])