如何在 Cython 中使用#define 作为 char 数组的大小

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

c++ 头文件 (some.h) 包含:

#define NAME_SIZE 42

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

我想在 Python 中使用 X 结构。我怎么做到的?

我写:

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

    ctypedef struct X:
        char name[NAME_SIZE + 1]

出现错误:常量表达式中不允许

NAME_SIZE 实际上并不存在于您的程序中,因此您可能必须在 Python.

中对其进行硬编码

尽管它在您的 C 源代码中看起来如何,您也在 C 数组声明中对其进行了硬编码。

在声明类型时告诉 Cython 什么通常并不重要 - 它使用信息来检查您在类型转换方面没有做任何明显错误的事情,仅此而已。 cdef extern "some.h" 语句确保将 some.h 包含到 Cython 创建的 c 文件中,并最终确定要编译的内容。

因此,在这种特殊情况下,您只需插入一个任意数字就可以了

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

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

在某些情况下它不会起作用,尤其是在 Cython 必须实际使用它生成的 C 代码中的数字的情况下。例如:

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

(我目前没有关于在这种情况下该怎么做的建议)