【问题标题】:Referencing Cython constants in Python在 Python 中引用 Cython 常量
【发布时间】:2018-07-11 21:30:39
【问题描述】:

我有一个 C 头文件(我们称之为 myheader.h),其中包含一些字符串定义,例如:

#define MYSTRING "mystring-constant"

在 Cython 中,我创建了一个 cmy.pxd 文件,其中包含:

cdef extern from "myheader.h":
    cdef const char* MYSTRING "MYSTRING"

还有一个相应的 my.pyx 文件,其中包含一些类定义,均以:

from cmy cimport *

然后我尝试在 Python 脚本中引用该字符串:

from my import *

def main():
     print("CONSTANT ", MYSTRING)

if __name__ == '__main__':
    main()

问题是我不断收到错误:

NameError: name 'MYSTRING' is not defined

我已搜索文档但无法确定问题所在。任何建议都会受到欢迎 - 我承认这可能真的很愚蠢。

【问题讨论】:

标签: cython cythonize


【解决方案1】:

您无法从 Python 访问 cdef 变量。因此,您必须创建一个与您的定义相对应的 Python 对象,如下所示(它使用 Cython>=0.28-feature verbatim-C-code,因此您需要最新的 Cython 版本来运行 sn-p):

%%cython
cdef extern from *:   
    """
    #define MYSTRING "mystring-constant"
    """
    # avoid name clash with Python-variable
    # in cdef-code the value can be accessed as MYSTRING_DEFINE
    cdef const char* MYSTRING_DEFINE "MYSTRING"

#python variable, can be accessed from Python
#the data is copied from MYSTRING_DEFINE   
MYSTRING = MYSTRING_DEFINE 

现在MYSTRING 是一个字节对象:

>>> print(MYSTRING)
b'mystring-constant'

【讨论】:

  • 这是一个很好的解决方案,谢谢!我想知道是否有办法在 cdef 代码和 python 代码中引用具有 same 名称的变量?这对于调试 cythonized .py 代码很有用。
猜你喜欢
  • 2014-06-25
  • 1970-01-01
  • 2012-10-22
  • 2010-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-18
  • 1970-01-01
相关资源
最近更新 更多