在Cython中定义字符串数组

时间:2018-12-01 16:40:31

标签: cython

此处停留在一些基本的Cython上-在Cython中定义字符串数组的规范有效的方法是什么?具体来说,我想定义{{1}的定长常量数组}。 (请注意,我现在不希望引入NumPy。)

在C中,它将是:

char

尝试使用Cython:

/* 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: language_level=3
# letters.pyx

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

2 个答案:

答案 0 :(得分:2)

您需要两行:

%%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)

另一个替代方法是以下一个衬垫:

%%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)不再可用。

答案 1 :(得分:2)

对于python3 Unicode字符串,这是可能的-

load

cdef Py_UNICODE* x[2] 
x = ["hello", "worlᏪd"]
相关问题