How to make memset with Python buffer object?

How to quickly reset to continue a set of values ​​inside a Python buffer object?

I'm mostly looking for memset :)

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

+6
source share
3 answers

The ctypes package has a built-in memset function. Ctypes works with Python 2.5, but it is not enabled by default. You will need a separate installation.

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' 
+2
source

If you can write, itertools.repeat ()

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

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

 size = ... buffer = bytearray(size) 

or perhaps:

 buffer[:] = bytearray(size) 
0
source

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


All Articles