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

2024-06-02 05:07:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码

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

^{pr2}$

Tags: the代码import内容bufferctypessomething缓冲区
2条回答

也许用^{}而不是{}分配缓冲区会更好。在这种情况下,您可以通过buf.生的. 在

如果您需要访问malloc()ed数据,可以使用^{},mybe与强制转换到ctypes.c_void_p或{}相结合,这取决于您对内存的其他操作以及包含的内容(以\0结尾的字符串或已知长度的数据)。在

将缓冲区转换为指向字节数组的指针,然后从中获取值。另外,如果您使用的是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)

相关问题 更多 >