我有一些python代码:
它使用ctypes来调用C例程,该例程位于共享库中.
这主要是有效的,除了实际写入文件.为了解压缩,我将未压缩的数据放入使用ctypes create_string_buffer方法创建的python缓冲区中:
c_uncompData_p = create_string_buffer(64000)
所以uncompression调用是这样的:
c_uncompSize = mylib.explodeCharBuffer (c_data_p, c_data_len, c_uncompData_p)
生成的未压缩数据的大小将作为返回值返回.
但是......我不知道如何强制python只写出c_uncompSize字节 - 如果我这样做:
myfile.write (c_uncompData_p.raw)
它将整个64k缓冲区写出来(数据是二进制的 - 所以它不是空终止的).
所以,我的问题是 - 使用Python 2.5如何打印出c_uncompSize字节,而不是整个64k?
谢谢杰米
切片也适用于c_char_Arrays:
myfile.write(c_uncompData_p[:c_uncompSize])
Run Code Online (Sandbox Code Playgroud)
buffer()可能有助于避免不必要的复制(由@ elo80ka的答案中的切片引起):
myfile.write(buffer(c_uncompData_p.raw, 0, c_uncompSize))
Run Code Online (Sandbox Code Playgroud)
在你的例子中它没关系(由于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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9768 次 |
| 最近记录: |