[英]Writing a binary buffer to a file in python
我有一些 python 代码:
它使用ctypes调用共享库中的 C 例程。
这主要是有效的,除了实际写入文件。 要解压缩,我将数据解压缩到 python 缓冲区中,使用 ctypes create_string_buffer
方法创建:
c_uncompData_p = create_string_buffer(64000)
所以解压调用是这样的:
c_uncompSize = mylib.explodeCharBuffer (c_data_p, c_data_len, c_uncompData_p)
生成的未压缩数据的大小作为返回值返回。
但是......我不知道如何强制 python 只写入c_uncompSize
字节 - 如果我这样做:
myfile.write (c_uncompData_p.raw)
它写出整个 64k 缓冲区(数据是二进制的 - 所以它不是 null 终止的)。
所以,我的问题是 - 使用 Python 2.5 如何打印出 c_uncompSize 字节,而不是整个 64k?
谢谢杰米
切片也适用于 c_char_Arrays:
myfile.write(c_uncompData_p[:c_uncompSize])
buffer()
可能有助于避免不必要的复制(由@elo80ka 的答案中的切片引起):
myfile.write(buffer(c_uncompData_p.raw, 0, c_uncompSize))
在您的示例中,这无关紧要(由于c_uncompData_p
只写一次而且很小),但总的来说它可能很有用。
只是为了练习,这里是使用 C stdio
的fwrite()
的答案:
from ctypes import *
# load C library
try: libc = cdll.msvcrt # Windows
except AttributeError:
libc = CDLL("libc.so.6") # Linux
# fopen()
libc.fopen.restype = c_void_p
def errcheck(res, func, args):
if not res: raise IOError
return res
libc.fopen.errcheck = errcheck
# errcheck() could be similarly defined for `fwrite`, `fclose`
# write data
file_p = libc.fopen("output.bin", "wb")
sizeof_item = 1 # bytes
nitems = libc.fwrite(c_uncompData_p, sizeof_item, c_uncompSize, file_p)
retcode = libc.fclose(file_p)
if nitems != c_uncompSize: # not all data were written
pass
if retcode != 0: # the file was NOT successfully closed
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.