ctypes variable length structures

前端 未结 6 1183
庸人自扰
庸人自扰 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:03

    You could use ctypes pointers to do this.

    C struct

    struct some_struct {
        uint  length;
        uchar data[1];
    };
    

    Python code

    from ctypes import *
    
    class SomeStruct(Structure):
        _fields_ = [('length', c_uint), ('data', c_ubyte)]
    
    #read data into SomeStruct
    s = SomeStruct()
    ptr_data = pointer(s.data)
    for i in range(s.length):
        print ptr_data[i]
    

提交回复
热议问题