How to use #define as size of char array in Cython

1k views Asked by At

c++ header (some.h) contains:

#define NAME_SIZE 42

struct s_X{
 char name[NAME_SIZE + 1]
} X;

I want to use X structure in Python. How could I make it?

I write:

cdef extern from "some.h":
    cdef int NAME_SIZE # 42

    ctypedef struct X:
        char name[NAME_SIZE + 1]

And got an error: Not allowed in a constant expression

2

There are 2 answers

0
DavidW On BEST ANSWER

It often doesn't really matter what you tell Cython when declaring types - it uses the information for checking you aren't doing anything obviously wrong with type casting and that's it. The cdef extern "some.h" statement ensures that some.h is included into to c-file Cython creates and ultimately that determines what is complied.

Therefore, in this particular case, you can just insert an arbitary number and it will work fine

cdef extern "some.h":
    cdef int NAME_SIZE # 42

    ctypedef struct X:
        char name[2] # you can pick a number at random here

In situations it won't work though, especially where Cython has to actually use the number in the C code it generates. For example:

def some_function():
  cdef char_array[NAME_SIZE+1] # won't work! Cython needs to know NAME_SIZE to generate the C code...
  # other code follows

(I don't currently have a suggestion as to what to do in this case)

0
Lightness Races in Orbit On

NAME_SIZE doesn't actually exist in your program so you'll probably have to hardcode it in the Python.

Despite how it looks in your C source code, you hardcoded it in the C array declaration, too.