How to print ctypes string buffer contents

I am creating a string buffer using the ctypes library in python. Now, if I have to print the contents of this string buffer later when it was written, how can I achieve this in python?

import ctypes
init_size = 256
pBuf = ctypes.create_string_buffer(init_size)
+4
source share
2 answers

You can use the properties .valueand .rawto access and manage. This is documented in this part of the ctypesdocs .

Here is the sample code from this section:

>>> 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
source

According to Python Ctypes docs: https://docs.python.org/2/library/ctypes.html

, .value object, ..:

print repr(pBuf.value) 

, io, - :

print "pBuff: %s" % pBuf.value
+1

Source: https://habr.com/ru/post/1671198/


All Articles