Python 等效于 C 结构(将应用程序从 C 移植到 python)

标签 python struct

我正在移植一个简单​​的蓝牙应用程序,它将 L2Cap 协议(protocol)上的“魔法”数据包发送到蓝牙设备..

我在将 C 中的结构对象转换为等效的 Python 时遇到问题..

在 c:

/* command types */
#define CFGBT_TYPE_SETREQ           0x00
#define CFGBT_TYPE_SETRES           0x01
#define CFGBT_TYPE_GETREQ           0x02
#define CFGBT_TYPE_GETRES           0x03

/* varid types */
#define CFG_VARIDT_UINT16                   0x0000
#define CFG_VARIDT_UINT32                   0x1000
#define CFG_VARIDT_STRING16                 0x2000

typedef struct {
    uint8_t      type, status;
    uint16_t     varid;
    uint8_t      value[16];
} __attribute__((packed)) CFGBTFRAME;

static CFGBTFRAME c;

然后在应用程序中它是这样使用的:

        /* set up */
    c.type = CFGBT_TYPE_GETREQ;
    c.varid = strtol(argv[3], NULL, 0);
    c.status = 0;
    memset(c.value, 0, 16);
    /* send frame */
    write(s, &c, sizeof(c));

你能告诉我如何使用 python 构建相同的数据包/类似结构的结构吗?

我知道我可能需要使用 ctypes 并创建“空”类,但如何将所有这些组合在一起?

最佳答案

您可以使用 struct 模块将值打包成字节字符串,例如:

>>> import struct
>>> type, status, varid, value = 1, 0, 16, b'Hello'
>>> buffer = struct.pack('>BBH16s', type, status, varid, value)
>>> buffer
b'\x01\x00\x00\x10Hello\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

或者,您可以使用ctypes.Structure 来定义一个将代表您的结构的类。它的优点是更易于与 Python 代码一起使用,但您必须考虑对齐和填充问题并自行解决(可能使用 struct)。

关于Python 等效于 C 结构(将应用程序从 C 移植到 python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7468168/

相关文章:

python - 属性错误: 'DataFrame' object has no attribute 'raw_ratings'

python - 如何在 python 2.7 中使用 numba jit 编译器提高 math.sqrt() 的速度

Python:在 Unicode 转义字符串上使用 .format()

swift - Swift 中的结构数组

c - 结构数组使用 malloc 时大小错误

python - Django 模型类中的多态性

python - 如何使用合适的 python 版本启动 python 程序?

C++ 将文本文件读入结构数据成员

不能使用结构体指针作为多个函数的参数

c++ - 正确初始化 OpenGL 的结构数组