Issue
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
Solution
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'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
Answered By - Mark Tolonen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.