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)
也许用^{} 而不是{}分配缓冲区会更好。在这种情况下,您可以通过buf.生的. 在
如果您需要访问} ,mybe与强制转换到}相结合,这取决于您对内存的其他操作以及包含的内容(以
malloc()
ed数据,可以使用^{ctypes.c_void_p
或{\0
结尾的字符串或已知长度的数据)。在将缓冲区转换为指向字节数组的指针,然后从中获取值。另外,如果您使用的是64位系统,则需要确保将
malloc
的返回类型设置为c_void_p
(不是默认的int
),这样返回值就不会丢失任何位。在您还需要小心,以防数据中有嵌入的NUL,您不能仅仅将指针转换为
c_char_p
并将其转换为字符串(如果您的数据根本没有以NUL结尾,则尤其如此)。在相关问题 更多 >
编程相关推荐