使用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)])