如何将通过 ctype malloc 分配的二进制缓冲区保存到 Python 中的文件?
我有以下代码
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)
I have the following code
import ctypes
pBuf = ctypes.cdll.msvcrt.malloc(nBufSize)
# wrote something into the buffer
How do I save the content of the buffer to a file using Python 2.5?
As you may already know, this is not going to work, giving TypeError: argument 1 must be string or read-only buffer, not int
:
f = open("out.data","wb"
f.write(pBuf)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许最好用
ctypes.create_string_buffer()< 分配缓冲区/code>
而不是
malloc()
。在这种情况下,您可以通过 buf.raw 访问数据。如果您需要访问
malloc()
ed 数据,可以使用ctypes.string_at(address, size)
, mybe 与转换为ctypes.c_void_p
或ctypes.c_char_p
,取决于您对内存执行的其他操作以及其中包含的内容(\0
终止的字符串或已知长度的数据)。Maybe it would better to have the buffer allocated with
ctypes.create_string_buffer()
instead ofmalloc()
. In this case, you have access to the data via buf.raw.If you need access to
malloc()
ed data, you can do so withctypes.string_at(address, size)
, mybe combined with a cast toctypes.c_void_p
orctypes.c_char_p
, depending on what else you do with the memory and what is contained (\0
terminated string or data with known length).将缓冲区转换为指向字节数组的指针,然后从中获取值。另外,如果您使用的是 64 位系统,则需要确保将
malloc
的返回类型设置为c_void_p
(不是默认的>int
),这样返回值就不会丢失任何位。您还需要小心,以防数据中嵌入了 NUL - 您不能只将指针转换为
c_char_p
并将其转换为字符串(如果是这样,则尤其如此)你的数据根本不是以 NUL 结尾的)。Cast the buffer into a pointer to a byte array, and then get the value from that. Also, if you're on a 64-bit system, you'll need to make sure to set the return type of
malloc
to ac_void_p
(not the defaultint
) so that the return value doesn't lose any bits.You'll also need to be careful, in case there are embedded NULs in your data -- you can't just convert the pointer into a
c_char_p
and convert that into a string (which is especially true if your data isn't NUL-terminated at all).