2009-09-18 13 views
5

Abbiamo alcuni file binari creati da un programma C.Come leggere una struttura contenente un array usando i ctypes di Python e readinto?

Un tipo di file viene creato chiamando fwrite di scrivere la seguente struttura C al file:

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

} easyStruc; 

In Python, ho letto le struct di questo file come segue:

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() 

Quello funziona bene. Il nostro altro tipo di file viene creato utilizzando la seguente struttura:

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

Non sono sicuro di come creare la struttura in Python.

risposta

9

Secondo questa documentation page (sezione:. 15.15.1.13 Array), dovrebbe essere qualcosa di simile:

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

Verificare che la pagina di documentazione per altri esempi.

+0

Grazie! Non sono sicuro di quanto mi sia mancato. –

2

C'è una sezione su arrays in ctypes nella documentazione. Fondamentalmente questo significa:

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