如何在Python中打印c_ubyte_Array对象?

时间:2022-03-16 21:42:21

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

在Python中打印C无符号字符数组的内容的最佳方法是什么?

if I use print theStruct.TheProperty

如果我用印刷体。

I get...

我得到……

<structs.c_ubyte_Array_8 object at 0x80fdb6c>

<结构。c_ubyte_array_8对象在0 x80fdb6c>

The definition is:

的定义是:

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

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

Desired output something like: Mr Smith

期望输出:史密斯先生。

1 个解决方案

#1


3  

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.

假设它是一个以null结尾的字符串,您可以将数组转换为char *并使用它的值。这里有一个例子,不是这样的。

>>> 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.

“Smith先生”填充了这个数组,所以对c_char_p的转换包括下一个字段的值,也就是9 (ASCII选项卡),谁知道还有什么,直到它达到一个空字节为止。

Instead you can iterate the array with join:

相反,您可以使用join迭代数组:

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

Or use a bytearray:

或者使用中bytearray:

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

Python 3:

Python 3:

>>> smith = Person((c_ubyte * 8)(*b'Mr Smith'), 9)
>>> bytes(smith.name).decode('ascii')
'Mr Smith'

#1


3  

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.

假设它是一个以null结尾的字符串,您可以将数组转换为char *并使用它的值。这里有一个例子,不是这样的。

>>> 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.

“Smith先生”填充了这个数组,所以对c_char_p的转换包括下一个字段的值,也就是9 (ASCII选项卡),谁知道还有什么,直到它达到一个空字节为止。

Instead you can iterate the array with join:

相反,您可以使用join迭代数组:

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

Or use a bytearray:

或者使用中bytearray:

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

Python 3:

Python 3:

>>> smith = Person((c_ubyte * 8)(*b'Mr Smith'), 9)
>>> bytes(smith.name).decode('ascii')
'Mr Smith'