gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:42:08 25 4
gpt4 key购买 nike

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]

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

最佳答案

在声明类型时告诉 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

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

关于python - 如何在 Cython 中使用#define 作为 char 数组的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30805744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com