Last active
March 30, 2018 02:24
-
-
Save JonathonReinhart/bf1e97ad642d2e829a9d553f918308be to your computer and use it in GitHub Desktop.
Populating an array member of a ctypes structure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import sys | |
from ctypes import * | |
assert sys.version_info >= (3,5) | |
class Struct(LittleEndianStructure): | |
_fields_ = [ | |
('a', c_uint32), | |
('b', c_uint32), | |
('c', c_uint32), | |
('buffer', c_uint8 * 32), | |
] | |
def getbytes(self): | |
return bytes(self) | |
def main(): | |
s = Struct( | |
a = 0x11111111, | |
b = 0x22222222, | |
c = 0x33333333, | |
) | |
# Option 1: read into | |
with open(__file__, 'rb') as f: | |
n = f.readinto(s.buffer) | |
print("Read {} bytes into buffer".format(n)) | |
print(s.getbytes().hex()) | |
# Option 2: assignment | |
# Annoying that you can't easily get the type of the 'buffer' field | |
# (https://stackoverflow.com/a/6061483/119527) | |
data = b'\x77' * 32 | |
artype = c_uint8 * 32 | |
s.buffer = artype(*data) | |
print(s.getbytes().hex()) | |
# Option 3: memmove() | |
data = b'\x66' * 32 | |
memmove(s.buffer, data, len(data)) | |
print(s.getbytes().hex()) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment