将C结构转换为Python以通过套接字发送

时间:2015-07-08 23:24:35

标签: python sockets struct swig ctypes

我目前正在更新用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,考虑到struct的大小和union语句的数量,这将非常困难。理想情况下,我想通过在C中生成结构来利用现有代码的某种方式,但不知何故通过字节转移到我的套接字的Python代码。有没有办法做到这一点?我已经研究过ctypes和swig,但是我没有看到从C代码获取字节表示的简单方法。

0 个答案:

没有答案