【发布时间】:2020-01-25 21:16:09
【问题描述】:
使用 Python 2.6,我创建了一个嵌套的 ctypes 结构如下:
class TestStruct1(BigEndianStructure):
_pack_ = 1
_fields_ = [
("temp1", c_uint32),
("temp2", c_uint32)
]
class TestStruct2(BigEndianStructure):
_pack_ = 1
_fields_ = [
("temp1", c_uint32),
("temp2", c_uint32)
]
class TestStruct3(BigEndianStructure):
_pack_ = 1
_fields_ = [
("TestStruct1", TestStruct1),
("TestStruct2", TestStruct2)
]
然后我将数据推送到这个结构中:
elements = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF]
data = bytes(elements)
foo = TestStruct3()
memmove(addressof(foo), data, sizeof(foo))
我可以将值一个一个打印出来,得到预期的输出:
print(format(foo.TestStruct1.temp1, '08X'))
print(format(foo.TestStruct1.temp2, '08X'))
print(format(foo.TestStruct2.temp1, '08X'))
print(format(foo.TestStruct2.temp2, '08X'))
00112233 44556677 8899AABB CCDDEEFF
但想利用 json.dumps 以 JSON 格式转储结构。这在 Python 3 中运行良好,如下所示:
https://onlinegdb.com/rJvQ0fFvS
但在 Python 2.6 中为无符号类型返回以下错误:
encoder.py",第 184 行,默认 raise TypeError(repr(o) + "不是 JSON 可序列化") TypeError: 1122867L 不是 JSON 可序列化的
我猜它被 1122867 中附加的“L”弄糊涂了L (0x00112233)
我是否必须在我的 JSONEncoder 类中添加某种无符号类型?
下面是我创建的一个显示问题的示例。运行脚本的主机上的字节序不同,因此输出不匹配,但它至少显示了操作中的错误:
https://rextester.com/UAWZK83752
任何帮助将不胜感激。
谢谢!
【问题讨论】: