使用dpkt的包,发现__repr__可以生成所有字段的打印值,而ctype生成的数据结构则只能给出<ctypes.c_byte_Array_4 object at 0x00BAB760>这种提示,不能给出详细的值,这在调试的时候很不方便,所以写了一段代码打印这些值。下面是代码:
from ctypes import *
class myStructure(Structure):
def __str__(self):
'''
l = [ '%s=%s' % (k, getattr(self, k)) for k,v in self._fields_]
return '%s(%s)' % (self.__class__.__name__, ', '.join(l))
'''
s=[]
for k,v in self._fields_:
if type(v)==type(c_int) or type(v)==type(Structure): #SimpleType
s.append("%s=%s"%(k,getattr(self,k)))
elif type(v)==type(Array):
s.append('%s=%s'%(k,'['+','.join(["%s" % getattr(self,k)[i] for i in range(v._length_)])+']'))
else:
pass
return '%s(%s)'%(self.__class__.__name__,','.join([i for i in s]))
class point(myStructure):
_fields_=[('x',c_int),('y',c_int)]
class rect(myStructure):
_fields_=[('p1',point),('p2',point)]
class rectlist(myStructure):
_fields_=[('num',c_int),('list',point*3)]
p1=point(1,1)
print p1
p2=point(2,2)
p3=point(3,3)
r=rect(p1,p2)
print r
rl=rectlist(3,(p1,p2,p3))
print rl
输出为:
point(x=1,y=1)
rect(p1=point(x=1,y=1),p2=point(x=2,y=2))
rectlist(num=3,list=[point(x=1,y=1),point(x=2,y=2),point(x=3,y=3)])