Stack allocated c arrays

41 views
Skip to first unread message

Brian Lester

unread,
Mar 28, 2018, 3:44:14 PM3/28/18
to cython-users
Hello I am trying to program a minimum edit distance program in cython and algorithm uses an internal table that is the size of the string 1 by size of string 2. This 2D array is just used inside of the function so it seems like I should just stack allocate it but this doesn't seem to work. I tried

```
cdef int n = len(string1)
cdef int m = len(string2)
cdef int table[n][m]
```
but this gives me the error of "Not allowed in a constant expression" This same error happens when I have n and m an parameters of the function. This seems like something I should be able to do. Stack allocating an array who's size depends on a parameter of the function is possible in C.

Does anyone have a solution to this? or should I use some other cython construct like a typed memory view? or do I have to make the table a pointer and malloc it to be the right size?

Pierre Complex

unread,
Apr 10, 2018, 9:55:19 AM4/10/18
to cython-users
Hi,

The "cdef" parts in Cython are close to what you can do in C. The syntax cdef int table[][] translates to a C array. C does not support multidimensional arrays out of the box.

Cython provides "typed memoryviews". Make sure to include "cimport numpy as np" in your code and write instead

cdef int[:,:] table = np.zeros(n,m)

will generate the array using NumPy but then you have the actual multidimensional array support from Cython.

The documentation of Cython covers this here: http://docs.cython.org/en/latest/src/userguide/memoryviews.html

Stefan Behnel

unread,
Apr 10, 2018, 1:59:08 PM4/10/18
to cython...@googlegroups.com
Pierre Complex schrieb am 10.04.2018 um 10:25:
> The "cdef" parts in Cython are close to what you can do in C. The syntax
> cdef int table[][] translates to a C array. C does not support
> multidimensional arrays out of the box.
>
> Cython provides "typed memoryviews". Make sure to include "cimport numpy as
> np" in your code and write instead
>
> cdef int[:,:] table = np.zeros(n,m)
>
> will generate the array using NumPy

Note that a "cimport" of the "numpy" module is not needed for the above
code to work, since you only have a runtime dependency on NumPy here, not a
compile time dependency. A normal "import" is sufficient. Memoryviews are
not a NumPy feature but a general Cython/CPython feature (through the
CPython buffer protocol).

Stefan
Reply all
Reply to author
Forward
0 new messages