如何打印 ctypes 字符串缓冲区的内容

How to print contents of ctypes string buffer

我正在 python 中使用 ctypes 库创建一个字符串缓冲区。 现在,如果我必须在写入后打印此字符串缓冲区的内容,我将如何在 python 中实现它?

import ctypes
init_size = 256
pBuf = ctypes.create_string_buffer(init_size)

您可以使用 .value.raw 属性来访问和操作它们。这在 this part of the ctypes docs.

中有详细记录

下面是该部分的一些示例代码:

>>> from ctypes import *
>>> p = create_string_buffer(3)            # create a 3 byte buffer, initialized to NUL bytes
>>> print(sizeof(p), repr(p.raw))
3 b'\x00\x00\x00'
>>> p = create_string_buffer(b"Hello")     # create a buffer containing a NUL terminated string
>>> print(sizeof(p), repr(p.raw))
6 b'Hello\x00'
>>> print(repr(p.value))
b'Hello'
>>> p = create_string_buffer(b"Hello", 10) # create a 10 byte buffer
>>> print(sizeof(p), repr(p.raw))
10 b'Hello\x00\x00\x00\x00\x00'
>>> p.value = b"Hi"
>>> print(sizeof(p), repr(p.raw))
10 b'Hi\x00lo\x00\x00\x00\x00\x00'
>>>

根据 Python Ctypes 文档: https://docs.python.org/2/library/ctypes.html

您应该能够使用 .value 对象打印字符串缓冲区值 属性 即:

print repr(pBuf.value) 

或者如果你想对 io 有一点兴趣,你可以使用类似的东西:

print "pBuff: %s" % pBuf.value