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).
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).
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'
If you can write into, try with itertools.repeat()
import itertools
my_buffer[:] = itertools.repeat(0, len(my_buffer))
:
means inside the square brace ? –
Helgahelge :
indicates that we are taking existing buffer as an iterator (all the elements of the buffer) and replace them with the newly created elements. It will replace the content of my_buffer
–
Gleason If you just want to set the values to zero, you can use this:
size = ...
buffer = bytearray(size)
or possibly:
buffer[:] = bytearray(size)
© 2022 - 2024 — McMap. All rights reserved.
buf[0]=chr(0)
but I want to write an entire set of values with speed instead of using for loops. – Onderdel
ling the name or binding it to another object is inadequate; the plaintext object could still persist in memory for a while before being garbage-collected. – Cornew