ctypes variable length structures

前端 未结 6 1160
庸人自扰
庸人自扰 2020-12-15 08:50

Ever since I read Dave Beazley\'s post on binary I/O handling (http://dabeaz.blogspot.com/2009/08/python-binary-io-handling.html) I\'ve wanted to create a Python library for

6条回答
  •  囚心锁ツ
    2020-12-15 09:16

    The most straightforward way, with the example you gave is to define the structure just when you have the information you need.

    A simple way of doing that is creating the class at the point you will use it, not at module root - you can, for example, just put the class body inside a function, that will act as a factory - I think that is the most readable way.

    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)
    

    Sorry - It is the C code that will "fill in" the values for you - that is not the answer them. WIll post another way.

提交回复
热议问题