如何优雅地发送/使用Python收到大量C结构? [英] How to elegantly send/receive a large C struct using Python?

查看:170
本文介绍了如何优雅地发送/使用Python收到大量C结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始写一个Python 3.x客户端应用程序。服务器应用程序的存在已经和正在用C写的服务器提供用于通过UDP发送和接收数据的两种结构(我用的定义C头文件Python的插座模块)。
的问题是,C结构是相当大的(约每200个元素)。如果我使用Python的结构模块包/解压缩数据,一个不那么完美的解决方案将包装/手动拆包的200个元素,如:

I have started to write a Python 3.x client application. The server application exists already and is written in C. The server provides a C header file with the definition of two structures used to send and receive data via UDP (I am using Python's socket module). The problem is that the C structures are quite large (around 200 elements each). If I use Python's struct module to pack/unpack the data, a not-so-elegant solution would be packing/unpacking the 200 elements manually, like:

struct.pack('H...I', data1, ..., data200)

此外,我希望能够访问接收使用类似C的语法/发送元素在Python。例如,如果我在C服务器端做

Furthermore, I want to be able to access the received/sent elements in Python using a C-like syntax. For example, if I do in the C server side

send.data.pos = pos;

这将是很好(最自然的),如果我可以访问 POS 在这样Python的客户端变量:

it would be nice (most natural) if I can access the pos variable in the Python client side like this:

pos = recv.data.pos

请注意,这个问题是的的如何自动从头文件用Python语言编写的结构,像的这个线程(我有一个在Python写的每个结构字段中的一个没有问题的),而是什么是组织在Python中的数据的最佳方式(如:在课堂上,使用字典等),让我利用Python的功能,并取得了code简单,数据易于访问(我宁愿只使用Python的标准模块,无需外部软件)。什么是最优雅的方式来实现这一目标?

Note that the question is not how to automatically write the structure in Python from the header file, like in this thread (I have no problem in writing each structure field one by one in Python), but rather what would be the best way to organise the data in Python (e.g. in classes, using dictionaries, etc.) that will allow me to exploit Python features and made the code simpler and the data easy to access (I'd rather use only Python standard modules, no external software). What would be the most elegant way to achieve this?

推荐答案

试试这个 - 工作在2.7和3.2

Try this -- works on 2.7 and 3.2.

脚本:

import struct, collections

class CStruct(object):

    def __init__(self, typename, format_defn, lead_char="!"):
        self.names = []
        fmts = [lead_char]
        for line in format_defn.splitlines():
            name, fmt = line.split()
            self.names.append(name)
            fmts.append(fmt)
        self.formatstr = ''.join(fmts)
        self.struct = struct.Struct(self.formatstr)
        self.named_tuple_class = collections.namedtuple(typename, self.names)

    def object_from_bytes(self, byte_str):
        atuple = self.struct.unpack(byte_str)
        return self.named_tuple_class._make(atuple)

if __name__ == "__main__":
    # do this once
    pkt_def = """\
        u1 B
        u2 H
        u4 I"""
    cs = CStruct("Packet1", pkt_def)
    # do this once per incoming packet
    o = cs.object_from_bytes(b"\xF1\x00\xF2\x00\x00\x00\xF4")
    print(o)
    print(o.u4)

输出:

Packet1(u1=241, u2=242, u4=244)
244

这篇关于如何优雅地发送/使用Python收到大量C结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆