在python中复制结构体



是否支持python中的结构,并且不支持正常的关键字结构?

例如

:

struct node
{
  unsigned dist[20];
  unsigned from[20];
}rt[10];

如何将其转换为python结构体?

我认为Python相当于c结构是classes:

class Node:
    def __init__(self):
        self.dist_ = []
        self.from_ = []
rt = []

由于属性的顺序(除非OrderedDict或其他东西用于__prepare__或以其他方式构建类)不一定按照定义的顺序,如果您想与实际的C struct兼容或依赖于某些顺序的数据,那么以下是您应该能够使用的基础(使用ctypes)。

from ctypes import Structure, c_uint
class MyStruct(Structure):
    _fields_ = [
        ('dist', c_uint * 20),
        ('from', c_uint * 20)
    ]

即使是空类也可以:

In [1]: class Node: pass
In [2]: n = Node()
In [3]: n.foo = [1,2,4]
In [4]: n.bar = "go"
In [8]: print n.__dict__
{'foo': [1, 2, 4], 'bar': 'go'}
In [9]: print n.bar
go

@Abhishek-Herle

如果我是你的话,我可能会依赖python中的Struct模块。

例如,在你的例子中,C结构是:
struct node
{
  unsigned dist[20];
  unsigned from[20];
}rt[10];

这里的基本思想是将C-Structure转换为python,反之亦然。我可以在下面的python代码中大致定义上面的c结构。

s = struct.Sturct('I:20 I:20') 

现在,如果我想将任何值打包到这个结构中,我可以这样做,如下所示:

dist = [1, 2, 3....20]
from = [1, 2, 3....20]
s.pack(*dist, *from)
print s #this would be binary representation of your C structure

显然,您可以使用s.p unpack方法解压缩它。

最新更新