ctypes可变长度结构 [英] ctypes variable length structures
问题描述
自从我阅读Dave Beazley关于二进制I / O处理的帖子(http://dabeaz.blogspot.com/2009/08/python-binary-io-handling.html)以来,我一直想创建一个Python库对于特定的有线协议。但是,我找不到可变长度结构的最佳解决方案。这是我想做的事情:
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 a certain wire protocol. However, I can't find the best solution for variable length structures. Here's what I want to do:
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!
]
类积分
由于尚未定义 num_points
,因此无法使用。一旦知道 num_points
后,我便可以重新定义 _fields _
变量,但是由于它是一个类变量,因此会影响所有其他 Points
实例。
The class Points
won't work since num_points
isn't defined yet. I could redefine the _fields_
variable later once num_points
is known, but since it's a class variable it would effect all of the other Points
instances.
什么是解决此问题的pythonic解决方案?
What is a pythonic solution to this problem?
推荐答案
最简单的方法是使用您给出的示例在需要信息时定义结构。
The most straightforward way, with the example you gave is to define the structure just when you have the information you need.
一种简单的实现方法是在点,您将使用它,而不是在模块根目录下使用-例如,您可以将 class
主体放入函数中,该函数将充当工厂-我认为那是
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)
对不起-
将为您填充值的C代码-不能回答它们。会以另一种方式发布。
Sorry - It is the C code that will "fill in" the values for you - that is not the answer them. WIll post another way.
这篇关于ctypes可变长度结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!