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

Nav*_*Nav 5 python ctypes

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

import ctypes
init_size = 256
pBuf = ctypes.create_string_buffer(init_size)
Run Code Online (Sandbox Code Playgroud)

agh*_*ast 3

您可以使用.value.raw属性来访问和操作它们。这在文档的这一部分的ctypes后面有记录。

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

>>> 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'
>>>
Run Code Online (Sandbox Code Playgroud)