How can I create this struct?

Question:

I want to create a struct like this:

import ctypes

class MyStruct(ctypes.Structure):
    _fields_ = [('field1', /* size of 16 bytes */),
                ('field2', /* size of 4 bytes */)
                ('field3', /* size of 8 bytes */)]

What is the types that i need to write here for these sizes of fields ? I want the the max size for field1 will be 16 bytes so the required value will be written there, and all the other bytes will be zeros (if necessary, up to 16 bytes). And in the same way for field2 and for field3.

Asked By: user20007266

||

Answers:

Two ways. The 16-bit field makes it a bit tricky:

import ctypes

class MyStruct(ctypes.Structure):
    _pack_ = 1
    _fields_ = (('field1', ctypes.c_ubyte * 16), # C char[16] field1
                ('field2', ctypes.c_uint32),     # C uint32_t field2
                ('field3', ctypes.c_uint64))     # C uint64_t field3
    def __init__(self,a,b,c):
        self.field1[:] = a.to_bytes(16,'little') # [:] trick to copy bytes to c_ubyte array
        self.field2 = b
        self.field3 = c

s = MyStruct(0x100, 0x200, 0x300)
print(bytes(s).hex(' '))

with open('out.bin','wb') as f:
    f.write(bytes(s))

# OR

import struct

b = struct.pack('<16sLQ',(0x100).to_bytes(16,'little'),0x200,0x300)
print(b.hex(' '))

with open('out.bin','wb') as f:
    f.write(b)

Output:

00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 03 00 00 00 00 00 00
00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 03 00 00 00 00 00 00
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.