cython - 在 Cython 中定义字符串数组

标签 cython

在这里停留在一些基本的 Cython 上 - 在 Cython 中定义字符串数组的规范且有效的方法是什么? 具体来说,我想定义一个定长常量数组char . (请注意,此时我不想引入 NumPy。)

在 C 中,这将是:

/* cletters.c */
#include <stdio.h>

int main(void)
{
    const char *headers[3] = {"to", "from", "sender"};
    int i;
    for (i = 0; i < 3; i++)
        printf("%s\n", headers[i]);
}

在 Cython 中尝试:
# cython: language_level=3
# letters.pyx

cpdef main():
    cdef const char *headers[3] = {"to", "from", "sender"}
    print(headers)

但是,这给出了:
(cy) $ python3 ./setup.py build_ext --inplace --quiet
cpdef main():
    cdef const char *headers[3] = {"to", "from", "sender"}
                               ^
------------------------------------------------------------

letters.pyx:5:32: Syntax error in C variable declaration

最佳答案

你需要两行:

%%cython
cpdef main():
    cdef const char *headers[3] 
    headers[:] = ['to','from','sender`]       
    print(headers)

有点违反直觉的是将 unicode 字符串(Python3!)分配给 char* .这是 Cython 的怪癖之一。另一方面,在仅使用一个值初始化所有内容时,需要字节对象:
%%cython
cpdef main():
    cdef const char *headers[3] 
    headers[:] = b'init_value`  ## unicode-string 'init_value' doesn't work.     
    print(headers)

另一种选择是以下oneliner:
%%cython
cpdef main():
    cdef const char **headers=['to','from','sender`]

    print(headers[0], headers[1], headers[2])

这与上面的不完全相同,并导致以下 C 代码:
  char const **__pyx_v_headers;
  ...
  char const *__pyx_t_1[3];
  ...
  __pyx_t_1[0] = ((char const *)"to");
  __pyx_t_1[1] = ((char const *)"from");
  __pyx_t_1[2] = ((char const *)"sender");
  __pyx_v_headers = __pyx_t_1;
__pyx_v_headers类型为 char **缺点是,print(headers)不再开箱即用。

关于cython - 在 Cython 中定义字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53572905/

相关文章:

python - 加快Python时间戳到日期时间的转换

python - 使用 Cython 将 np.ndarray 传递到 Fortran

python - 如何在 Cython 中包装匿名枚举并为其命名?

python - 如何在cython中切片列表

python - 从 Python 中的字符串创建重叠子字符串列表的最快方法

cython - 分发 python 包时处理 dylibs

python - PySide/Cython 和 GIL 多线程使用

python - 将Python转换为C,然后用Cython编译成exe

python - Cython 优化 numpy 数组求和的关键部分

python - 如何解决错误 "error compiling Cython file"错误?