在python3环境上运行create_string_buffer时出现问题

问题描述 投票:0回答:1

这是我的示例Python 3代码。

from ctypes import create_string_buffer
import struct
...

# self.payload is None / max is integer
self.payload = create_string_buffer(max)

# self.payload is ctypes.c_char_Array_3
struct.pack_into(str(max) + "s", self.payload, 0, padding)

这是错误代码

struct.error: argument for 's' must be a bytes object

此示例代码在Python2环境中运行良好。但是,以上错误代码是在转换为python3的过程中发现的。

因此,我将self.payload强制转换为bytes(self.payload.raw)类型会导致以下错误代码。

TypeError: argumnet must be read-write bytes-like object, not bytes

我们如何解决这些错误并在python3环境中运行它们?

python-3.x ctypes
1个回答
0
投票

列出[Python 3.Docs]: struct - Interpret strings as packed binary data

关于字符串,事情在Python 2Python 3之间发生了变化。检查[SO]: Passing utf-16 string to a Windows function (@CristiFati's answer)了解更多详细信息。

尽管它只是可猜测的(因为问题缺少代码的相关部分(写得不好)),罪魁祸首是payload,因为那是与“ * s相对应的参数” >”格式(与self.payload完全无关)。因此,该行实际上应该是:

struct.pack_into(str(length) + "s", self.payload, 0, padding.encode())

此外,在对内置函数进行阴影处理时,请对max

使用另一个名称。
© www.soinside.com 2019 - 2024. All rights reserved.