[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]
Re: [pygame] BufferProxy (was Flood Filling Images)
Brian Fisher wrote:
I dislike adding numpy/numeric as a dependency, and previously I sped
some stuff up by making an array from a string, modifying the array,
then making a new surface from the modified array as a string vs.
getting and setting pixels, so I would love it if I could just do
stuff like:
---
surface = Surface((1,1), 32)
surface_contents = surface.get_buffer()
surface_contents[3] = 0
---
or whatever...
Be careful what you wish for ;-).
++++++++++++++ bytearray.py ++++++++++++++++
import pygame
import ctypes
if hasattr(ctypes.pythonapi, 'Py_InitModule4'):
Py_ssize_t = ctypes.c_int
elif hasattr(ctypes.pythonapi, 'Py_InitModule4_64'):
Py_ssize_t = ctypes.c_int64
else:
raise TypeError("Cannot determine type of Py_ssize_t")
PyObject_AsWriteBuffer = ctypes.pythonapi.PyObject_AsWriteBuffer
PyObject_AsWriteBuffer.restype = ctypes.c_int
PyObject_AsWriteBuffer.argtypes = [ctypes.py_object,
ctypes.POINTER(ctypes.c_void_p),
ctypes.POINTER(Py_ssize_t)]
def array(surface):
buffer_interface = surface.get_buffer()
address = ctypes.c_void_p()
size = Py_ssize_t()
PyObject_AsWriteBuffer(buffer_interface,
ctypes.byref(address), ctypes.byref(size))
bytes = (ctypes.c_byte * size.value).from_address(address.value)
bytes.object = buffer_interface
return bytes
+++++++++++++++++++++++++++++++++++++++
>>> import pygame
>>> import bytearray
>>> im = pygame.Surface((10,10), pygame.SRCALPHA, 32)
>>> im.get_at((0,0))
(0, 0, 0, 0)
>>> a = bytearray.array(im)
>>> a[0:4] = (0,1,2,3)
>>> del a
>>> im.get_at((0,0))
(2, 1, 0, 3)
I have no idea what happens if you try this with a subsurface.
--
Lenard Lindstrom
<len-l@xxxxxxxxx>