Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cython C-array initialization

Tags:

cython

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.

like image 640
Danilo Horta Avatar asked Sep 22 '14 13:09

Danilo Horta


2 Answers

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]
like image 119
Veedrac Avatar answered Oct 22 '22 05:10

Veedrac


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.

like image 7
kirr Avatar answered Oct 22 '22 05:10

kirr