How to do a memset with Python buffer object?
Asked Answered
O

3

6

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

Onder answered 25/11, 2011 at 15:4 Comment(3)
how do you create your buffer object ?Gleason
It is returned by WxImage.GetDataBuffer(), you can write to it using buf[0]=chr(0) but I want to write an entire set of values with speed instead of using for loops.Onder
Just a comment.. memset could be useful when handling cryptographically sensitive data. Example: destroying the plaintext password after encrypting it. delling 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
B
3

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'
Bellerophon answered 25/11, 2011 at 19:17 Comment(0)
T
1

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

import itertools
my_buffer[:] = itertools.repeat(0, len(my_buffer))
Telespectroscope answered 25/11, 2011 at 15:55 Comment(2)
What does that : means inside the square brace ?Helgahelge
@shuva those : 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_bufferGleason
P
1

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

size = ...
buffer = bytearray(size)

or possibly:

buffer[:] = bytearray(size)
Perlie answered 25/11, 2011 at 23:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.