bytearray throwing error for python class object when ctype structure present as class attributes

Question:

I was able to convert ctype class object into bytearray() using below method –

from ctypes import *

class get_log_input_payload(Structure):
    _pack_ = 1
    _fields_ = (
        ("log_identifier",c_uint8*16),
        ("offset",c_uint32),
        ("length",c_uint32)
    )
payload = get_log_input_payload()
b_array = bytearray(payload)

but when we used ctype class as an attributes inside python class, bytearray() started throwing error "TypeError: cannot convert ‘_ctypes.PyCStructType’ object to bytearray"

from ctypes import *

class Mailbox:
    get_log_input_payload = type("get_log_input_payload", (Structure, ), {"_fields_" : [("log_identifier",c_uint8*16),
                                                                                        ("offset",c_uint32),
                                                                                        ("length",c_uint32)]})

obj = Mailbox()
payload = obj.get_log_input_payload 
b_array = bytearray(payload) # <--- Throwing error

Note:
Updated typo in the code

Asked By: DHARMESH PITRODA

||

Answers:

Not sure why you are making a class manually with type, but there are two errors in the provided code. There is a missing colon(:) in the type call after the _fields_ key, and then the type must be instantiated:

from ctypes import *

class Mailbox:
    get_log_input_payload = type("get_log_input_payload", (Structure, ), {"_fields_": [("log_identifier",c_uint8*16),
#                                                                     missing colon ^                                                                                        ("offset",c_uint32),
                                                                                        ("length",c_uint32)]})

obj = Mailbox()
payload = obj.get_log_input_payload()  # missing () to instantiate the type
b_array = bytearray(payload)
print(b_array)

Output:

bytearray(b'x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00')
Answered By: Mark Tolonen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.