How to do a memset with Python buffer object?

sorin picture sorin · Nov 25, 2011 · Viewed 10.1k times · Source

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).

Answer

Peter Shinners picture Peter Shinners · Nov 25, 2011

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'