【问题标题】:How to use const in Cython如何在 Cython 中使用 const
【发布时间】:2014-07-15 10:27:13
【问题描述】:

我已在此链接中阅读:https://github.com/cython/cython/wiki/FAQ#id35 我的 Cython 0.20.1 应该能够支持 const。

但是我的以下代码无法编译:

cdef const double a = 2.5
print(a)

在编译期间它说

test.pyx:5:5: Assignment to const 'a'
Traceback (most recent call last):
  File "setup1.py", line 11, in <module>
    ext_modules = cythonize(extensions)
  File "X:\WinPython3\python-3.3.5.amd64\lib\site-packages\Cython\Build\Dependencies.py", line 785, in cythonize
    cythonize_one(*args[1:])
  File "X:\WinPython3\python-3.3.5.amd64\lib\site-packages\Cython\Build\Dependencies.py", line 902, in cythonize_one
    raise CompileError(None, pyx_file)
Cython.Compiler.Errors.CompileError: test.pyx

【问题讨论】:

  • 我认为cdef enum 是您在 cython 中声明 const 的方式,但枚举是整数,所以我想它在您的情况下不起作用。
  • @PadraicCunningham 谢谢 - 解决了我的问题!
  • 不客气。我认为您可以使用 DEF 声明一个 const 但它是无符号的。虽然我认为它适用于你的情况。
  • @PadraicCunningham:我认为它是一种文字替换,就像 C 预处理器一样。所以不管是什么类型。

标签: python constants cython


【解决方案1】:

const 适用于函数参数,但不适用于此构造,因为 Cython 如何将其编译为 C。

cdef double a = 2.5

变成

double __pyx_v_a;
/* lots of other declarations */

__pyx_v_a = 2.5;

这不适用于const 变量。实际上,您不能在 Cython 中使用 const 在所有可以在 C 中使用它的地方。

【讨论】:

  • 谢谢!考虑 Cython 在 C 中的工作方式真的很有帮助。
  • C++ 呢?我们可以让 Cython 编译成 C++,对吧?然后可以像我们在 c++ 中那样使用 const 吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-25
  • 1970-01-01
  • 1970-01-01
  • 2021-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多