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

我在
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'
>>>
点赞