2009-09-18 3 views
5

우리는 C 프로그램에 의해 생성 된 일부 이진 파일을 가지고 있습니다. 파일의파이썬의 ctypes와 readinto를 사용하여 배열을 포함하는 구조체를 읽는 방법?

한 유형이 파일에 다음 C 구조를 작성하기에 fwrite를 호출하여 생성 다음과 같이 파이썬에서

typedef struct { 
    unsigned long int foo; 
    unsigned short int bar; 
    unsigned short int bow; 

} easyStruc; 

를,이 파일의 구조체를 읽어

class easyStruc(Structure): 
    _fields_ = [ 
    ("foo", c_ulong), 
    ("bar", c_ushort), 
    ("bow", c_ushort) 
] 

f = open (filestring, 'rb') 

record = censusRecord() 

while (f.readinto(record) != 0): 
    ##do stuff 

f.close() 

을 그 잘 작동합니다. 다른 유형의 파일은 다음 구조를 사용하여 생성됩니다.

typedef struct { // bin file (one file per year) 
    unsigned long int foo; 
    float barFloat[4]; 
    float bowFloat[17]; 
} strucWithArrays; 

저는 파이썬에서 구조를 만드는 방법을 모르겠습니다.

답변

9

documentation page (섹션. : 15.15.1.13 배열)에 따르면

class strucWithArrays(Structure): 
    _fields_ = [ 
    ("foo", c_ulong), 
    ("barFloat", c_float * 4), 
    ("bowFloat", c_float * 17)] 

확인 다른 예는 해당 설명서 페이지, 그것은 뭔가 같이해야합니다.

+0

감사합니다! 내가 그걸 어떻게 놓쳤는 지 잘 모르겠다. –

2

설명서에 arrays in ctypes에 관한 섹션이 있습니다. 기본적으로 의미 :

class structWithArray(Structure): 
    _fields_ = [ 
     ("foo", c_ulong), 
     ("barFloat", c_float * 4), 
     ("bowFloat", c_float * 17) 
    ] 
관련 문제