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 会得到正确的字符串输出。

相关内容

热门资讯

技术分享!wepoker有没有... 技术分享!wepoker有没有插件(辅助挂)果然是真的有挂(有挂存在)暗藏猫腻,小编详细说明wepo...
玩家必知教程!wpk软件是正规... 玩家必知教程!wpk软件是正规的吗(辅助挂)都是存在有挂(有人有挂)1、金币登录送、破产送、升级送、...
六分钟了解!德普辅助app(辅... 六分钟了解!德普辅助app(辅助挂)总是有挂(有挂方略)1)德普辅助app辅助插件:进一步探索德普辅...
分享一款!wpk真的有透视嘛(... 分享一款!wpk真的有透视嘛(辅助挂)确实真的是有挂(有挂秘籍)wpk真的有透视嘛辅助器是一种具有地...
每日必看推荐!wepoker透... 每日必看推荐!wepoker透视脚本苹果版(辅助挂)竟然真的有挂(有挂分析)1、实时wepoker透...
分享给玩家!wepoker到底... 分享给玩家!wepoker到底有没有透视(辅助挂)原来有挂(有挂解密)1、wepoker到底有没有透...
实测教程!hhpoker开挂教... 实测教程!hhpoker开挂教程(辅助挂)果然真的有挂(有挂详细)1、首先打开hhpoker开挂教程...
科技通报!拱趴大菠萝挂怎么安装... 科技通报!拱趴大菠萝挂怎么安装(辅助挂)都是真的是有挂(今日头条)1)拱趴大菠萝挂怎么安装有没有挂:...
必看攻略!模拟器打开hhpok... 必看攻略!模拟器打开hhpoker(辅助挂)真是有挂(有挂实锤)必看攻略!模拟器打开hhpoker(...
教程攻略!大菠萝免费辅助器(辅... 教程攻略!大菠萝免费辅助器(辅助挂)竟然真的有挂(有挂分享)一、大菠萝免费辅助器游戏安装教程牌型概率...