1

I want to define a C array in my Cython code, which I understand does not work with dynamic variables, e.g. this does not work:

cdef int length = 30
cdef np.double_t[length] carr

I read here that it is possible to define static variables at compilation time for this purpose but I get a compilation error when I try to cast the variable like this:

DEF int length = 30
...

The Error reads:

Expected '=', found 'length'

And I likewise get an understandable error when I try to go without casting:

Array dimension not integer

Someone else has asked a similar question here but did not receive any answers.

Is it possible to define a variable at compilation time to use later on to set the size of a C array?

Daniel
  • 430
  • 1
  • 4
  • 12
  • 2
    `cdef np.double_t carr[length]` (and don't specify `int` with `DEF`) Note the dimension is after the variable name, which is consistent with both C, and the [examples given in the Cython documentation](https://cython.readthedocs.io/en/latest/src/userguide/language_basics.html#compile-time-definitions). I've voted to close as a typo – DavidW Oct 11 '18 at 20:29
  • Thank you, that solves my problem! But how is it that I can go without casting in the DEF declaration? Are these values automatically cast or does the creation of a C array not require ints? – Daniel Oct 12 '18 at 08:28
  • 2
    The `DEF` statement is like the C preprocessor - it's a literal text replacement. Wherever it sees length it just substitutes the number in the source code (therefore it doesn't need a type) – DavidW Oct 12 '18 at 09:03

1 Answers1

0

Cython's DEF is now being deprecated. If you will try to run in in the newest version of Cython, you will get following deprecation warning:

The 'DEF' statement is deprecated and will be removed in a future Cython version. Consider using global variables, constants, and in-place literals instead. See https://github.com/cython/cython/issues/4310

Recommended pre-compile definition of constants is now like this:

cdef const int length = 30
Fusion
  • 5,046
  • 5
  • 42
  • 51
  • What do you suggest for constants used in fused type expressions? For example, a constant that is some floating point value (ex. `2.2`), but is used in code with `cython.floating` and could be a 32-bit or 64-bit float? If I do as you suggest then I have to choose 32 or 64 and C will have to cast it right? – djhoese Aug 02 '23 at 17:22