vitiral
vitiral

Reputation: 9220

How to use python ctypes with a bytearray?

How do I use python's ctypes library to read/write from a bytearray?

I can create a structure like below:

from ctypes import *

class Foo(Structure):
    _fields_ = [
        ('b0', c_byte),
        ('b1', c_byte),
        ('s0', c_short),
        ('l0', c_long),
    ]

f = Foo(1, 0x42, 0xF00F, 0x12345678)

But dir(Foo) does not show any way to create a Foo from a bytearray and dir(f) doesn't show any way to convert a Foo into a bytearray or write to a bytearray. Am I missing something?

Upvotes: 1

Views: 1008

Answers (1)

vitiral
vitiral

Reputation: 9220

Note: this combines these two answers

Say we have the following type

from ctypes import *

class Foo(Structure):
    _fields_ = [
        ('b0', c_byte),
        ('b1', c_byte),
        ('s0', c_short),
        ('l0', c_long),
    ]

f = Foo(1, 0x42, 0xF00F, 0x12345678)

You can get the value as bytes simply by using bytearray:

f_bytearray = bytearray(f)

Similarly, if you want to mutate a bytearray you can do so:

b = bytearray(32)
b[10:10+sizeof(f)] = f

If you want to convert a bytearray into a structure you can do so using from_buffer

Note: for some reason in python3, from_buffer is not included in dir(Foo).

# shares the buffer: mutating f will mutate f_bytearray
f = Foo.from_buffer(f_bytearray)
# OR copies the data to a new buffer
f = Foo.from_buffer_copy(f_bytearray)

Bonus: you can get offset information from (for example) Foo.l0.offset. With this you should be able to read/write a struct to a bytearray no problem :D

Upvotes: 3

Related Questions