代码之家  ›  专栏  ›  技术社区  ›  Brad Solomon

在Cython中定义字符串数组

  •  2
  • Brad Solomon  · 技术社区  · 7 年前

    在Cython中定义字符串数组的规范有效方法是什么? 具体来说,我想定义一个固定长度的常量数组 char

    在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
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   ead    7 年前

    您需要两行:

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

    有点违反直觉的是,将unicode字符串(Python3!)分配给 char* . 这是Cython的怪癖之一。另一方面,当只使用一个值初始化所有内容时,需要bytes对象:

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

        2
  •  3
  •   Dev Aggarwal    7 年前

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

    cdef Py_UNICODE* x[2] 
    x = ["hello", "worlᏪd"]
    

    cdef Py_UNICODE** x
    x = ["hello", "worlᏪd"]
    
    推荐文章