1

This is my sample Python 3 code.

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)

This is Error Code

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

This sample code worked well in Python2 environment. However, the above error code was found during the conversion process to python3.

So, I forced conversion of self.payload to bytes(self.payload.raw) type results in the following Error Code.

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

How do we fix these errors and run them in a python3 environment?

1 Answers1

1

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

Things have changed between Python 2 and Python 3 regarding strings. Check [SO]: Passing utf-16 string to a Windows function (@CristiFati's answer) for more details.

Although it's only guessable (as the question lacks relevant portions of the code (it's poorly written)), the culprit is payload, because that's the argument that corresponds to the "*s" format (and it's not at all related to self.payload). So, the line should actually be:

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

Also, use another name for max (e.g. length), as you're shadowing the built-in function.

CristiFati
  • 38,250
  • 9
  • 50
  • 87