How to do a memset with Python buffer object?

11,519

Solution 1

The ctypes package has a memset function built right in. Ctypes does work with Python 2.5, but is not included by default. You will need a separate install.

def memsetObject(bufferObject):
    "Note, dangerous"
    import ctypes
    data = ctypes.POINTER(ctypes.c_char)()
    size = ctypes.c_int()  # Note, int only valid for python 2.5
    ctypes.pythonapi.PyObject_AsCharBuffer(ctypes.py_object(bufferObject), ctypes.pointer(data), ctypes.pointer(size))
    ctypes.memset(data, 0, size.value)

testObject = "sneakyctypes"
memsetObject(testObject)
print repr(testObject)
# '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

Solution 2

If you can write into, try with itertools.repeat()

import itertools
my_buffer[:] = itertools.repeat(0, len(my_buffer))

Solution 3

If you just want to set the values to zero, you can use this:

size = ...
buffer = bytearray(size)

or possibly:

buffer[:] = bytearray(size)
Share:
11,519
sorin
Author by

sorin

Another geek still trying to decipher the meaning of “42”. It seems that amount his main interest are: online communities of practice and the way they evolve in time product design, simplicity in design and accessibility productivity and the way the IT solutions are impacting it

Updated on June 04, 2022

Comments

  • sorin
    sorin almost 2 years

    How can I do a fast reset for a continue set of values inside a Python buffer object?

    Mainly I am looking for a memset :)

    PS. The solution should work with Python 2.5 and modify the buffer itself (no copy).