【问题标题】:How to convert a cython char* filled with 0x00 to non-empty byte array如何将用 0x00 填充的 cython char* 转换为非空字节数组
【发布时间】:2023-02-22 05:24:59
【问题描述】:

这是一个cython函数:

cdef struct my_struct_t:
    unsigned int a
    short b
    unsigned char[6] c

cdef void f_my_struct_t(int buff_size, const unsigned char* buf, list output):
    cdef:
        my_struct_t *arr = <my_struct_t *> buf
        list data = []

    for i in range(buff_size / sizeof(my_struct_t)):
        data.append(arr[i])

    output.append({
        "type": "my_struct_t",
        "data": data
    })

该函数接受一个包含结构my_struct_t 的缓冲区参数,并将该结构格式化为 json 格式。

在 C 中,char* 只是一个字节数组。
在 cython 中,它被认为是一个只包含 ASCII 字符的数组。
因此,如果第一个元素是 0x00 别名 '\0',它将字节数组转换为 b''。而如果 char 数组仅包含 0x00,则应将其转换为 b'000000'

这个函数的当前结果是:

 {
    'type': 'my_struct_t',
    'data': [
      {
        'a': 1,
        'b': 2,
        'c': b'' # Byte array should not be null
      }
    ]
  }

json.dumps(xxx, indent=4) 如何用空字节数组解析这个字典?目前如果因为这个空的字节数组而失败(或者可能只是因为有一个字节数组?)。 当前错误:TypeError: Object of type bytes is not JSON serializable

如何强制 cython 将 char* 正确转换为字节数组?

【问题讨论】:

    标签: python json cython python-bytearray


    【解决方案1】:
    1. 它不是因为它是空的而失败——它失败是因为它是字节而不是字符串。您需要通过执行 bytes_value.decode("ascii")(或您可能使用的任何其他编码)将其转换为字符串。

    2. 默认情况下,Cython 将 char 数组视为 C 字符串并在 处停止

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-15
    • 2015-08-23
    • 1970-01-01
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多