Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #67691 > unrolled thread

Re: how to get bytes from bytearray without copying

Started byJuraj Ivančić <juraj.ivancic@gmail.com>
First post2014-03-04 16:23 +0100
Last post2014-03-04 16:23 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: how to get bytes from bytearray without copying Juraj Ivančić <juraj.ivancic@gmail.com> - 2014-03-04 16:23 +0100

#67691 — Re: how to get bytes from bytearray without copying

FromJuraj Ivančić <juraj.ivancic@gmail.com>
Date2014-03-04 16:23 +0100
SubjectRe: how to get bytes from bytearray without copying
Message-ID<mailman.7722.1393946633.18130.python-list@python.org>
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.

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web