utypes调用

Viewed 16

问题描述


以前通过一个嵌套层次比较深的json数据作为配置读写

现在想要实现union联合体效果,将经常使用的参数重新组合,使得字节数组和某对象共用相同数据源,使得配置读取既紧凑又灵活,但是案例跑不通,是哪里写的不对吗,一点运行效果没有,K230会卡住

import uctypes

# 内存布局
serial_layout = {
    "data1": 0 | uctypes.UINT16,
    "data2": 4 | uctypes.UINT32,
    "x": 0 | uctypes.FLOAT32
}

# 分配底层字节缓冲
buf = bytearray(8) 

# 创建 struct 对象
serial = uctypes.struct(buf, serial_layout)

# 写数据
serial.data1=1
serial.data2=10
serial.x = 1.23

# 查看底层字节数组
print(list(buf))

硬件板卡


庐山派

软件版本


CanMV v1.4-2-g873d625(based on Micropython e00a144) on 2025-09-12; k230_canmv_lckfb with K230

1 Answers

你创建的struct不对,参考下面的代码:

import uctypes

# 内存布局
serial_layout = {
    "data1": 0 | uctypes.UINT16,
    "data2": 0 | uctypes.UINT32,
    "x": 0 | uctypes.FLOAT32
}

# 分配底层字节缓冲
buf = bytearray(8) 

## 创建 struct 对象
serial =uctypes.struct(uctypes.addressof(buf), serial_layout, uctypes.LITTLE_ENDIAN)
print(serial)

## 写数据
serial.data1=1
serial.data2=10
serial.x = 1.23

# 查看底层字节数组
print(list(buf))