Cython: creating an array throws “not allowed in a constant expression”

后端 未结 1 1741
青春惊慌失措
青春惊慌失措 2021-01-21 17:36

I try to rewrite a complex function form Python to Cython to speed it up massively and I encounter the following problem: while compiling my function hh_vers_vector.pyx using

相关标签:
1条回答
  • 2021-01-21 17:42

    cdef in Cython is for C definitions, as the name implies. Therefore the code

    cdef float v[10000]
    

    is translated to the following C code

    float v[10000];
    

    Meaning a static float array of size 10k, defined at compile time.

    This, on the other hand

    cdef float v[numSamples]
    

    Would translate to the C code

    int numSamples = <..>;
    float v[numSamples];
    

    This is an attempt to compile a static array containing a variable number of elements, which is not valid C. Hence the 'constant expression error'.

    Either use a python list to store the floats, or dynamically allocate C arrays via malloc/free.

    0 讨论(0)
提交回复
热议问题