<p>可以使用<a href="https://docs.python.org/2/library/ctypes.html#ctypes.Structure" rel="noreferrer">^{<cd1>}</a>或<a href="https://docs.python.org/2/library/struct.html#struct.Struct" rel="noreferrer">^{<cd2>}</a>指定文件的格式。要从<a href="https://stackoverflow.com/a/17244645/4279">C code in @perreal's answer</a>生成的文件中读取结构:</p>
<pre class="lang-py prettyprint-override"><code>"""
struct { double v; int t; char c;};
"""
from ctypes import *
class YourStruct(Structure):
_fields_ = [('v', c_double),
('t', c_int),
('c', c_char)]
with open('c_structs.bin', 'rb') as file:
result = []
x = YourStruct()
while file.readinto(x) == sizeof(x):
result.append((x.v, x.t, x.c))
print(result)
# -> [(12.100000381469727, 17, 's'), (12.100000381469727, 17, 's'), ...]
</code></pre>
<p>见<a href="https://docs.python.org/3/library/io.html#io.BufferedIOBase.readinto" rel="noreferrer">^{<cd3>}</a>。它在Python3中受支持,但在Python2.7中没有针对<a href="https://docs.python.org/2/library/stdtypes.html#bltin-file-objects" rel="noreferrer">default file object</a>的文档。</p>
<p><code>struct.Struct</code>需要显式指定填充字节(<code>x</code>):</p>
<pre class="lang-py prettyprint-override"><code>"""
struct { double v; int t; char c;};
"""
from struct import Struct
x = Struct('dicxxx')
with open('c_structs.bin', 'rb') as file:
result = []
while True:
buf = file.read(x.size)
if len(buf) != x.size:
break
result.append(x.unpack_from(buf))
print(result)
</code></pre>
<p>它产生相同的输出。</p>
<p>为避免不必要的复制,<a href="https://docs.python.org/2/library/ctypes.html#ctypes._CData.from_buffer" rel="noreferrer">^{<cd6>}</a>可用于从文件中获取结构数组:</p>
<pre class="lang-py prettyprint-override"><code>import mmap # Unix, Windows
from contextlib import closing
with open('c_structs.bin', 'rb') as file:
with closing(mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_COPY)) as mm:
result = (YourStruct * 3).from_buffer(mm) # without copying
print("\n".join(map("{0.v} {0.t} {0.c}".format, result)))
</code></pre>