我有以下代码

import ctypes
pBuf = ctypes.cdll.msvcrt.malloc(nBufSize)
# wrote something into the buffer

如何使用Python2.5将缓冲区的内容保存到文件中?
正如你可能已经知道的,这是行不通的,给TypeError: argument 1 must be string or read-only buffer, not int
f = open("out.data","wb"
f.write(pBuf)

最佳答案

将缓冲区转换为指向字节数组的指针,然后从中获取值。此外,如果您使用的是64位系统,则需要确保将malloc的返回类型设置为c_void_p(不是默认的int),以便返回值不会丢失任何位。
您还需要小心,以防数据中有嵌入的nul——您不能只是将指针转换为c_char_p并将其转换为字符串(如果您的数据根本没有以nul结尾,这一点尤其正确)。

malloc = ctypes.dll.msvcrt.malloc
malloc.restype = ctypes.c_void_p

pBuf = malloc(nBufSize)
...
# Convert void pointer to byte array pointer, then convert that to a string.
# This works even if there are embedded NULs in the string.
data = ctypes.cast(pBuf, ctypes.POINTER(ctypes.c_ubyte * nBufSize))
byteData = ''.join(map(chr, data.contents))

with open(filename, mode='wb') as f:
    f.write(byteData)

10-07 13:18
查看更多