2

I would like to create a 2D-array within a cdef function with the number of elements in each dimension depending on parameters passed to the function. E.g.:

cdef int[:,:] c_volumecheck(int n):

    cdef:
        const int comb = 2**n
        const int nt = n
        int match[comb][nt] 
        size_t i,j

    # initialize values
    for i in range(comb):
        for j in range(n):
            match[i][j] = 0


return match

However, assigning to comb and nt a constant expression does not seem to work as I get the error "Not allowed in a constant expression" in line int match[comb][nt]. Manually providing the respective values work (match[8][3] for e.g. n=3). That is not an option however, as these values change during the program.

The second thing is, that I do not seem to understand how to return this array to another cdef or def function in the same .pyx-script: int[:,:] does not seem to correspond to a 2d-array like the one I want to initialize.

Cœur
  • 37,241
  • 25
  • 195
  • 267
user3820991
  • 2,310
  • 5
  • 23
  • 32
  • 1
    `int[:,:]` is the syntax for a typed memoryview; I"d suggest reading/experimenting with this doc page: http://cython.readthedocs.io/en/latest/src/userguide/memoryviews.html – hpaulj Jun 05 '17 at 17:22
  • believe me, I was'nt lazy before I posted my question. But I couldn't find a reference on how to return an array. However, consulting the [c-turorials](https://www.tutorialspoint.com/cprogramming/c_return_arrays_from_function.htm), it might be the case that it is not intended to be able to return arrays, as you cannot do so in C as well, only pointers to arrays. – user3820991 Jun 05 '17 at 18:28
  • 1
    Can you explain what the calling function is supposed to see? Is this a purely C level operation, or do you expect to return something useful to Python code (lists, numpy arrays)? – hpaulj Jun 05 '17 at 18:47
  • it is supposed to return to a `def` function in the `pyx'-script. I could probably keep it within a 'cdef' environment. But I will definitly not use the value outside cython. – user3820991 Jun 06 '17 at 09:08
  • Then is this just standard `c` coding, modified a bit by `cython` syntax? – hpaulj Jun 06 '17 at 09:28
  • yes, that's what i thought. – user3820991 Jun 06 '17 at 09:34
  • Which means that you cannot return an array or memoryview, as it is at the C level. You can pass pointers around however. You can use optimize your code partially by keeping it as a "def" function and return a NumPy array. This will take care of memory allocation, a useful byproduct. For your example: `cdef double[:,:] myarray = np.zeros((2**n, n))` would replace the intialization part of your function. – Pierre de Buyl Jun 06 '17 at 13:35
  • https://stackoverflow.com/questions/25917593/how-to-declare-2d-c-arrays-dynamically-in-cython suggests memoryviews as an alternative to static C arrays. – hpaulj Jun 06 '17 at 19:29

0 Answers0