How to use Cython typed memoryviews to accept strings from Python?

后端 未结 2 1343
伪装坚强ぢ
伪装坚强ぢ 2021-02-07 12:32

How can I write a Cython function that takes a byte string object (a normal string, a bytearray, or another object that follows the buffer protocol) as a typed memoryview?

2条回答
  •  悲哀的现实
    2021-02-07 12:48

    This issue was fixed in Cython 0.28, released 2018-03-13 (PR #1869). The changelog says:

    The const modifier can be applied to memoryview declarations to allow read-only buffers as input.

    There is also a new section in the documentation.

    The example you gave will work in Cython 0.28 if you write your function like this:

    cpdef object printbuf(const unsigned char[:] buf):
        chars = [chr(x) for x in buf]
        print repr(''.join(chars))
    

提交回复
热议问题