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

相关内容

热门资讯

分享实测!HH平台挂,hhpo... 分享实测!HH平台挂,hhpoker到底可以作弊码,一直有挂(有挂细节)1、实时透视辅助更新:用户可...
据目击者称!hhpoker辅助... 据目击者称!hhpoker辅助器,德普之星透视辅助软件,本来是有挂(有挂方法)1、下载好德普之星透视...
玩家必备教程!wpk作弊,约局... 玩家必备教程!wpk作弊,约局吧app有挂吗,果然真的是有挂(有挂教程)1、下载好透视辅助下载之后点...
2026版方法!hhpoker... 2026版方法!hhpoker到底可以作弊吗,德普之星透视辅助插件,都是确实有挂(有人有挂);在进入...
每日必看!epoker有透视吗... 每日必看!epoker有透视吗,约局吧透视挂下载,总是真的是有挂(有挂功能);透视方法中分为三种模型...
为切实保障!xpoker辅助控... 为切实保障!xpoker辅助控制,德普之星透视辅助插件,本来真的是有挂(有挂规律)1、德普之星透视辅...
查到实测辅助!hhpoker到... 查到实测辅助!hhpoker到底可以作弊吗,wpk辅助购买,其实存在有挂(确实有挂)1、起透看视 辅...
据公告内容!wepoker怎么... 您好,智星德州有脚本吗这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩...
技巧知识分享!hhpoker真... 技巧知识分享!hhpoker真的有透视吗,pokermaster破解版,真是是真的有挂(有挂解密)在...
针对!wepoker透视器免费... 针对!wepoker透视器免费,德普之星私人局透视,确实确实有挂(今日头条)1、打开软件启动之后找到...