ctypes可变长度结构

Jak*_*ake 13 python ctypes python-3.x

自从我读到Dave Beazley关于二进制I/O处理的帖子(http://dabeaz.blogspot.com/2009/08/python-binary-io-handling.html)以来,我一直想创建一个特定的Python库.电线协议.但是,我找不到可变长度结构的最佳解决方案.这就是我想要做的事情:

import ctypes as c

class Point(c.Structure):
    _fields_ = [
        ('x',c.c_double),
        ('y',c.c_double),
        ('z',c.c_double)
        ]

class Points(c.Structure):
    _fields_ = [
        ('num_points', c.c_uint32),
        ('points', Point*num_points) # num_points not yet defined!
        ]
Run Code Online (Sandbox Code Playgroud)

该类Points将无法工作,因为num_points尚未定义.我可以_fields_稍后重新定义变量num_points,但由于它是一个类变量,它会影响所有其他Points实例.

什么是这个问题的pythonic解决方案?

jsb*_*eno 11

最简单的方法,您给出的示例是在您拥有所需信息时定义结构.

一个简单的方法是在你将使用它的时候创建类,而不是在模块根目录 - 你可以,例如,只需将class主体放在一个函数中,它将充当工厂 - 我认为这是最多的可读的方式.

import ctypes as c



class Point(c.Structure):
    _fields_ = [
        ('x',c.c_double),
        ('y',c.c_double),
        ('z',c.c_double)
        ]

def points_factory(num_points):
    class Points(c.Structure):
        _fields_ = [
            ('num_points', c.c_uint32),
            ('points', Point*num_points) 
            ]
    return Points

#and when you need it in the code:
Points = points_factory(5)
Run Code Online (Sandbox Code Playgroud)

对不起 - 这是为您"填写"值的C代码 - 这不是他们的答案.将以另一种方式发布.