how to get bytes from bytearray without copying

Juraj Ivančić juraj.ivancic at gmail.com
Tue Mar 4 16:23:32 CET 2014


On 3.3.2014. 2:27, Ian Kelly wrote:

> Python 3.3 has a C API function to create a memoryview for a char*,
> that can be made read-only.
>
>      http://docs.python.org/3/c-api/memoryview.html#PyMemoryView_FromMemory
>
> I don't see a way to do what you want in pure Python, apart from
> perhaps writing an elaborate proxy class that would just be a poor
> man's memoryview.  Or you could bite the bullet and copy everything
> once at the start to create a bytes object, and then never have to
> worry about it again.

Just for reference, it is doable in pure Python, with ctypes help:

pydll = ctypes.cdll.LoadLibrary("python{}{}".format(
     sys.version_info.major, sys.version_info.minor))

def ro_memoryview_from_bytearray(buffer):
     assert isinstance(buffer, bytearray)
     ptr = ctypes.c_char_p(pydll.PyByteArray_AsString(
         ctypes.py_object(buffer)))
     mv_id = pydll.PyMemoryView_FromMemory(ptr, len(buffer), 0)
     return ctypes.cast(mv_id, py_object).value

Note that this is just the jist, in real code I added safeguards to 
prevent misuse of the (temporary) memoryview.





More information about the Python-list mailing list