Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #67691
| From | Juraj Ivančić <juraj.ivancic@gmail.com> |
|---|---|
| Subject | Re: how to get bytes from bytearray without copying |
| Date | 2014-03-04 16:23 +0100 |
| References | <lf0h3g$m7r$1@ger.gmane.org> <CALwzidncPvJS_aPJENre2HfOvV_PoY8mSV4PGA+i8FcwYPFc=A@mail.gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.7722.1393946633.18130.python-list@python.org> (permalink) |
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.
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: how to get bytes from bytearray without copying Juraj Ivančić <juraj.ivancic@gmail.com> - 2014-03-04 16:23 +0100
csiph-web