将C结构转换成Python并通过s发送

2024-09-19 23:33:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在更新一个旧的,用C编写的大型软件,它通过一个套接字向服务器发送一个结构。更新后的软件将用Python编写,这意味着我现在需要以与Python中的C结构相同的字节布局发送相同的信息。我知道Python包结构,并希望使用它。问题是,这个结构绝对是巨大的。为了给你一个主意,这里有一个告密者:

// this is the struct that I wish to send 

typedef struct
{
    struct st_command_header header;

    union {
        char buffer[32];
        struct set_360_camera_message camera_msg;
        struct u_olcd_msg olcd_msg;
    };   

} struct_to_be_set stc;


// supporting structs

struct st_command_header
{
  union  u_all_types len;
  union  u_all_types cmd;
  union  u_all_types cmd_counter;
  union  u_all_types items;
} __attribute__((packed));

struct u_olcd_msg
{  
  // over 100 lines of fields to fill
}

// all the other structs necessary

据我所知,struct python包需要手动打包结构,考虑到struct的大小和union语句的数量,这将非常困难。理想情况下,我希望通过某种方式利用现有代码,即用C生成结构,但以某种方式将字节传输到套接字的Python代码中。有办法吗?我已经研究过ctypes和swig,但是我没有看到从C代码中获取字节表示的简单方法。在


Tags: theto代码字节msgall结构struct