Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print contents of ctypes string buffer

Tags:

python

ctypes

I am creating a string buffer using ctypes library in python. Now if I have to print contents of this string buffer later when it has been written, how will i achieve that in python?

import ctypes
init_size = 256
pBuf = ctypes.create_string_buffer(init_size)
like image 260
BlackCoffee Avatar asked Mar 02 '17 00:03

BlackCoffee


2 Answers

You can use the .value and .raw properties to access and manipulate them. This is documented far down in this part of the ctypes docs.

Here is some of the example code from that 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'
>>>
like image 189
aghast Avatar answered Nov 07 '22 07:11

aghast


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

You should be able to print the string buffer value using the .value object property ie:

print repr(pBuf.value) 

Or if you want to get a bit fancy with the io you can use something like:

print "pBuff: %s" % pBuf.value
like image 1
David Watson Avatar answered Nov 07 '22 05:11

David Watson