gh-112015: Implement ctypes.memoryview_at() (GH-112018)

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
Co-authored-by: Petr Viktorin <encukou@gmail.com>
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
This commit is contained in:
Rian Hunter 2025-01-03 05:07:07 -08:00 committed by GitHub
parent f21af186bf
commit b4f799b1e7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 120 additions and 1 deletions

View file

@ -2182,6 +2182,28 @@ Utility functions
.. audit-event:: ctypes.wstring_at ptr,size ctypes.wstring_at
.. function:: memoryview_at(ptr, size, readonly=False)
Return a :class:`memoryview` object of length *size* that references memory
starting at *void \*ptr*.
If *readonly* is true, the returned :class:`!memoryview` object can
not be used to modify the underlying memory.
(Changes made by other means will still be reflected in the returned
object.)
This function is similar to :func:`string_at` with the key
difference of not making a copy of the specified memory.
It is a semantically equivalent (but more efficient) alternative to
``memoryview((c_byte * size).from_address(ptr))``.
(While :meth:`~_CData.from_address` only takes integers, *ptr* can also
be given as a :class:`ctypes.POINTER` or a :func:`~ctypes.byref` object.)
.. audit-event:: ctypes.memoryview_at address,size,readonly
.. versionadded:: next
.. _ctypes-data-types:
Data types

View file

@ -343,6 +343,14 @@ ctypes
* On Windows, the :func:`~ctypes.CopyComPointer` function is now public.
(Contributed by Jun Komoda in :gh:`127275`.)
* :func:`ctypes.memoryview_at` now exists to create a
:class:`memoryview` object that refers to the supplied pointer and
length. This works like :func:`ctypes.string_at` except it avoids a
buffer copy, and is typically useful when implementing pure Python
callback functions that are passed dynamically-sized buffers.
(Contributed by Rian Hunter in :gh:`112018`.)
datetime
--------