Skip to content

Instantly share code, notes, and snippets.

@jn0
Last active August 16, 2018 16:42
Show Gist options
  • Save jn0/82e1fbb07e2dce5a457f5ec2c5a808a9 to your computer and use it in GitHub Desktop.
Save jn0/82e1fbb07e2dce5a457f5ec2c5a808a9 to your computer and use it in GitHub Desktop.
import ctypes as c
import string
import logging; log = logging.getLogger(__name__)
# ...
def dump(obj, logger=log.info):
# assert isinstance(obj, c.C_TYPE)
B = []
C = []
offset = 0
last = ''
count = 0
raw = c.cast(c.addressof(obj), c.POINTER(c.c_char * c.sizeof(obj))).contents.raw # THIS IS WHAT YOU'RE LOOKING FOR
logger('%s size: %u = 0x%x', '*' * 8, len(raw), len(raw))
for x in raw:
C.append(x if x in string.printable and not x.isspace() else '.')
B.append('%02x' % (ord(x),))
if len(C) == 16:
s = ' '.join(B) + ' ' + ''.join(C)
if last != s:
if count:
logger('%s %s', '*' * 8, count)
count = 0
logger('%08x %s', offset, s)
last = s
else:
count += 1
offset += 16
while C: C.pop()
while B: B.pop()
if count:
logger('%s %s', '*' * 8, count)
if C:
while len(C) < 16:
C.append(' ')
B.append(' ')
logger('%08x %s %s', offset, ' '.join(B), ''.join(C))
# EOF #
@jn0
Copy link
Author

jn0 commented Aug 16, 2018

Code like

import ctypes as c
# ...
b10 = c.c_char(10)()
b10.value = '\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a'
dump(b10)

Writes something like

INFO:MyMod:******** size: 10 = 0xa
INFO:MyMod:00000000 01 02 03 04 05 06 07 09 0a                    ..........

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment