4

What is the best way to print the contents of a C unsigned char array in Python,

if I use print theStruct.TheProperty

I get...

<structs.c_ubyte_Array_8 object at 0x80fdb6c>

The definition is:

class theStruct(Structure): _fields_ = [("TheProperty", c_ubyte * 8)]

Desired output something like: Mr Smith

2
  • The best way to print any object is the one that gives the desired output. Nothing more than this can be said until you do not specify what your desired output is. Commented Nov 19, 2012 at 13:25
  • I came here looking how to print elements of a ctypes structure. Short form: in python3, wrap it in a bytes() constructor and you can treat it like any Python array. Commented Jul 20, 2020 at 16:36

1 Answer 1

4

Assuming it's a null-terminated string, you can cast the array to a char * and use its value. Here's an example where that's not the case.

>>> class Person(Structure): _fields_ = [("name", c_ubyte * 8), ('age', c_ubyte)]
... 
>>> smith = Person((c_ubyte * 8)(*bytearray('Mr Smith')), 9)
>>> smith.age
9
>>> cast(smith.name, c_char_p).value
'Mr Smith\t'

"Mr Smith" fills up the array, so casting to c_char_p includes the value of the next field, which is 9 (ASCII tab), and who knows what else, however much until it reaches a null byte.

Instead you can iterate the array with join:

>>> ''.join(map(chr, smith.name))
'Mr Smith'

Or use a bytearray:

>>> bytearray(smith.name)
bytearray(b'Mr Smith')

Python 3:

>>> smith = Person((c_ubyte * 8)(*b'Mr Smith'), 9)
>>> bytes(smith.name).decode('ascii')
'Mr Smith'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.