You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建指定字节大小的ctypes结构体?

使用ctypes定义指定字节大小的结构体

要满足你指定的字节大小要求,同时支持写入值后剩余字节补零,可按以下方式选择ctypes类型:

字段类型选择

  • field1(16字节):用ctypes.c_char * 16,这是固定长度的字节数组。赋值短字符串时会自动在末尾补零;若内容超过16字节,会自动截断为前16字节。
  • field2(4字节):用ctypes.c_char * 4,逻辑同field1,固定4字节长度,自动补零或截断。
  • field3(8字节):用ctypes.c_char * 8,固定8字节长度,自动补零或截断。

完整代码示例

import ctypes

class MyStruct(ctypes.Structure):
    _fields_ = [
        ('field1', ctypes.c_char * 16),
        ('field2', ctypes.c_char * 4),
        ('field3', ctypes.c_char * 8)
    ]

# 使用示例
if __name__ == "__main__":
    struct_inst = MyStruct()
    
    # 赋值短字符串,自动补零
    struct_inst.field1 = b"sample text"
    struct_inst.field2 = b"123"
    struct_inst.field3 = b"demo"
    
    # 验证字节内容
    print("field1内容:", struct_inst.field1)  # 输出: b'sample text\x00\x00\x00\x00\x00'
    print("field2内容:", struct_inst.field2)  # 输出: b'123\x00'
    print("field3内容:", struct_inst.field3)  # 输出: b'demo\x00\x00\x00\x00'

替代方案(针对非字符串字节操作)

如果需要精细控制每个字节(比如处理二进制数据),可以用无符号字节数组类型:

class MyStruct(ctypes.Structure):
    _fields_ = [
        ('field1', ctypes.c_ubyte * 16),
        ('field2', ctypes.c_ubyte * 4),
        ('field3', ctypes.c_ubyte * 8)
    ]

# 手动赋值并补零
struct_inst = MyStruct()
data = b"custom bytes"
struct_inst.field1[:len(data)] = data
# 剩余字节设为0
for i in range(len(data), 16):
    struct_inst.field1[i] = 0

内容的提问来源于stack exchange,提问作者user20007266

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 00:20:53