30

I would like to do

cdef int mom2calc[3]
mom2calc[0] = 1
mom2calc[1] = 2
mom2calc[2] = 3

in a more compact way. Something similar to

cdef int mom2calc[3] = [1, 2, 3]

which is an invalid Cython syntax.

Note:

cdef int* mom2calc = [1, 2, 3]

is not an option because I cannot (automatically) converted it to a memory view.

Danilo Horta
  • 403
  • 1
  • 4
  • 5

4 Answers4

38
cdef int mom2calc[3]
mom2calc[:] = [1, 2, 3]

This works on raw pointers (although it isn't bounds checked then), memory views and fixed-sized arrays. It only works in one dimension, but that's often enough:

cdef int mom2calc[3][3]
mom2calc[0][:] = [1, 2, 3]
mom2calc[1][:] = [4, 5, 6]
mom2calc[2][:] = [7, 8, 9]
0 _
  • 10,524
  • 11
  • 77
  • 109
Veedrac
  • 58,273
  • 15
  • 112
  • 169
  • 1
    You can do it in one line as such: `cdef int[3][3] arr2d = [range(3), (3, 4, 5), [6, 7, 8]]`. Note this works nicely with various iterable types too. – Matt Eding Jan 09 '20 at 23:55
8
cdef int[3] mom2calc = [1, 2, 3]

This is how it should be done. Example of C-array initialization in Cython tests is e.g. here.

kirr
  • 391
  • 4
  • 8
0

Note that this is not currently easy to do with the nogil option, see this github bug: https://github.com/cython/cython/issues/3160

Scott
  • 504
  • 6
  • 17
0

For multidimensional arrays the syntax is:

cdef int[3][3] arr = [[1, 2, 3], [4, 5, 6], [6, 7, 8]]

Notice where the array size [3][3] is placed right after the type.

Ben Souchet
  • 1,450
  • 6
  • 20