bytearray中包含空字符的PyByteArray_AsString的解决方案
创始人
2025-01-12 21:00:20
0

由于 PyByteArray_AsString 只适用于不含空字符的 bytearray,如果在 bytearray 中含有空字符,转换为字符串会出现错误。但是可以通过使用 PyUnicode_AsUTF8AndSize 和 PyBytes_FromStringAndSize 函数来解决该问题。

以下是代码示例:

import ctypes
import sys

PY3 = sys.version_info[0] == 3

if PY3:
    get_buffer = memoryview
    unicode_type = str
    xrange = range
else:
    def get_buffer(m):
        return m

    unicode_type = unicode


def bytearray_as_string(bytearray_obj):
    buf = get_buffer(bytearray_obj)
    size = len(bytearray_obj)

    # Find the index of the first null character
    null_idx = -1
    for i in xrange(size):
        if buf[i] == b'\0':
            null_idx = i
            break

    if null_idx == -1:
        # No null characters found, use PyByteArray_AsString
        return ctypes.c_char_p(buf).value
    else:
        # Convert to PyUnicodeObject first
        # Use PyUnicode_AsUTF8AndSize to convert to UTF-8 encoded bytes
        # Use PyBytes_FromStringAndSize to convert the bytes to string
        unicode_obj = PyUnicode_DecodeUTF8(ctypes.c_char_p(buf).value, size, NULL)
        return PyBytes_AsString(PyUnicode_AsUTF8String(unicode_obj))


# Usage example
bytearray_obj = b'hello\0world'
print(bytearray_as_string(bytearray_obj))

使用 bytearray_as_string 函数来转换带空字符的 bytearray 会得到正确的字符串输出。

相关内容

热门资讯

揭露透视!德扑圈有透视吗,微乐... 揭露透视!德扑圈有透视吗,微乐游戏辅助脚本安装,要领教程(有人有挂)-哔哩哔哩1、德扑圈有透视吗免费...
有挂透视!wepoker插件功... 有挂透视!wepoker插件功能辅助器,微信微乐陕西小程序破解器,大纲教程(详细教程)-哔哩哔哩1)...
揭幕透视!wepoker私人局... 揭幕透视!wepoker私人局俱乐部辅助,微乐春天扑克开挂辅助插件,项目教程(新版有挂)-哔哩哔哩1...
总结透视!智星德州插件最新版本... 总结透视!智星德州插件最新版本更新内容详解,微乐云南小程序辅助器,策略教程(有挂秘诀)-哔哩哔哩1、...
辅助透视!德州私人局怎么透视,... 辅助透视!德州私人局怎么透视,如何下载微乐自建房黑科技入口,法门教程(揭秘有挂)-哔哩哔哩德州私人局...
揭露透视!wepoker怎么看... 揭露透视!wepoker怎么看牌型,微乐小程序辅助器脚本,大纲教程(有挂教程)-哔哩哔哩1、完成we...
开挂透视!wpk真吗,小程序微... 开挂透视!wpk真吗,小程序微乐陕西挖坑辅助器,练习教程(讲解有挂)-哔哩哔哩1、下载好wpk真吗正...
教你透视!pokerworld... 教你透视!pokerworld修改器,微乐小程序辅助多少钱,项目教程(详细教程)-哔哩哔哩1、上手简...
曝光透视!wepoker有用吗... 曝光透视!wepoker有用吗,微乐山西脚本插件,办法教程(证实有挂)-哔哩哔哩1.wepoker有...
专业透视!aapoker俱乐部... 专业透视!aapoker俱乐部靠谱吗,微乐河南家乡麻将辅助脚本,指引教程(真实有挂)-哔哩哔哩小薇(...