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

时间:2017-03-02 00:13:19

标签: python ctypes

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

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

2 个答案:

答案 0 :(得分:1)

您可以使用.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'
>>>

答案 1 :(得分:1)

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

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

print repr(pBuf.value) 

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

print "pBuff: %s" % pBuf.value