PythonでCのunsignedchar配列の内容を出力するための最良の方法は何ですか?
使用する場合print theStruct.TheProperty
わかった...
<structs.c_ubyte_Array_8 object at 0x80fdb6c>
定義は次のとおりです。
class theStruct(Structure):
_fields_ = [("TheProperty", c_ubyte * 8)]
必要な出力は次のようになります。
Mr Smith
nullで終了する文字列であると仮定すると、配列をにキャストして、char *そのを使用できますvalue。これが当てはまらない例を次に示します。
>>> 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'
「MrSmith」は配列をいっぱいにするので、にキャストするc_char_pと、次のフィールドの値(9(ASCIIタブ))が含まれ、nullバイトに達するまで、他に何がわかっているかがわかります。
代わりに、次のように配列を繰り返すことができますjoin。
>>> ''.join(map(chr, smith.name))
'Mr Smith'
または、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'