如何将通过ctype malloc分配的二进制缓冲区保存到Python文件中?

1 投票
2 回答
2237 浏览
提问于 2025-04-17 04:42

我有以下代码

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

我该如何用Python 2.5把缓冲区的内容保存到一个文件里呢?

你可能已经知道,这样做是行不通的,会出现错误:TypeError: argument 1 must be string or read-only buffer, not int

f = open("out.data","wb"
f.write(pBuf)

2 个回答

4

也许用 ctypes.create_string_buffer() 来分配缓冲区会更好,而不是用 malloc()。这样的话,你可以通过 buf.raw 来访问数据。

如果你需要访问用 malloc() 分配的数据,可以使用 ctypes.string_at(address, size),可能还需要结合 ctypes.c_void_pctypes.c_char_p 来转换,这取决于你对内存的其他操作以及里面包含的内容(比如是以 \0 结尾的字符串,还是已知长度的数据)。

3

把缓冲区转换成一个指向字节数组的指针,然后从中获取值。如果你使用的是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)

撰写回答