Cython/CUDA wrapper for numpy arrays

31 views
Skip to first unread message

Rory Johnston

unread,
Sep 28, 2022, 1:26:29 PM9/28/22
to cython-users
I'm trying to write a Cython interface that would allow me to pass in a numpy array to my Cython library, and have it interpreted as a C++ array with dimensions that are deduced from the input numpy array. These dimensions would then be used to allocate memory on the GPU using CUDA. I'm largely using this project, but would like to change the behaviour to allow for any-dimensional arrays (without having to flatten beforehand).

The behaviour I'd like is this:

```
import numpy as np
import cpy   # this is my Cython/CUDA ext
A  = np.zeros((M,N))
Ac = cpy.array(A)
```
i.e. similar to what CuPy does.

What I currently want to be able to do if I can get it to work is:

```
import numpy as np
cimport numpy as np

cdef extern from "array.h":
    cdef cppclass C_array "array":
        void C_array(np.float32_t*, int*, int)

cdef class array:
    cdef C_array* cpy_array
    cdef uint* shape
    cdef uint length, size, ndim

    cdef __init__(self, np.ndarray[dtype=np.float32_t] numpy_array):

        self.ndim  = numpy_array.ndim
        self.shape = numpy_array.shape
        self.cpy_array = new C_array(&numpy_array[0], self.shape, self.ndim)

    def __del__(self):
        del self.cpy_array
```

This interface is compiled as an `ext` in `setup.py` to create `cpy`, which I want to be able to import in Python, use to instantiate C++ arrays from numpy arrays, then send back the numpy arrays when requested.

I know the [pseudo-]code is wrong on many levels, but if someone could show me a way to interpret numpy arrays of any dimension in Cython in a manner like this, I'd really appreciate it.
Reply all
Reply to author
Forward
0 new messages