Reputation: 4956
I've defined a structure:
class test(Structure):
_fields_ = [('char_array', c_char * 255)]
a = test()
# prints <class 'bytes'>
print(type(a.char_array))
Why is this type bytes
and not type bytearray
?
I'm unable to change values in char_array
because bytes doesn't support item assignment. i.e: a.char_array[0] = 1
This isn't the case if instead I were to use c_int
; just curious why ctypes is converting this to a bytes
object and not leaving it as c_char_Array_255
like it would if it were c_int * 255
?
How do I convert it to a bytearray
and still modify the structure accordingly?
Upvotes: 2
Views: 1443
Reputation: 140186
Type c_char
maps to immutable type.
Use type c_byte
to be able to modify that. Example:
from ctypes import *
class test(Structure):
_fields_ = [('char_array', c_byte * 255)]
a = test()
print(type(a.char_array))
a.char_array[0]=ord('e')
a.char_array[1]=ord('x')
print(bytes(a.char_array).decode())
prints ex
Upvotes: 2