Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
236657b
Implement `ctypes.buffer_at()`
rianhunter Nov 13, 2023
55d7690
Fix typo
rianhunter Nov 13, 2023
00e3c23
Apply suggestions from code review
rianhunter Jan 18, 2024
df0f992
Make size argument a Py_ssize_t, per @serhiy-storchaka suggestion
rianhunter Jan 19, 2024
eaa2d13
Add what's new entry
rianhunter Jan 19, 2024
db3a26a
Rename buffer_at to memoryview_at
rianhunter Jan 19, 2024
d7e2f25
Make mutable objects the default
rianhunter Jan 19, 2024
097a41c
Add test for ctypes.memoryview_at
rianhunter Jan 19, 2024
4fe9b44
Merge in the main branch; move What's New entry
encukou Sep 18, 2024
e2c2609
TMP
encukou Sep 18, 2024
d39bb42
Merge in the main branch
encukou Nov 29, 2024
3a6b559
Revert to calling through `ctypes` to get `c_void_p` conversion seman…
encukou Nov 29, 2024
375081a
Test read-only memoryview
encukou Nov 29, 2024
b9e8572
Use c_ssize_t for the size
encukou Nov 29, 2024
1a33fe3
Test size overflow
encukou Nov 29, 2024
0198c89
Doc fixups. Don't imply that *readonly* makes the memory immutable.
encukou Nov 29, 2024
6b0a8ae
Fixups
encukou Nov 29, 2024
e4af54f
Merge branch 'main' into ctypes-buffer-at
encukou Dec 12, 2024
5600cef
Apply suggestions from code review
encukou Dec 19, 2024
c3c9e17
Avoid extra variable
encukou Dec 19, 2024
d1ca15d
Merge in the main branch
encukou Dec 19, 2024
d41a201
Remove unneeded line
encukou Dec 20, 2024
f3b1987
Merge in the main branch
encukou Dec 20, 2024
82a6659
Merge in the main branch
encukou Jan 2, 2025
400a62d
Remove unneeded line
encukou Jan 2, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions Doc/library/ctypes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2109,6 +2109,23 @@ Utility functions
.. audit-event:: ctypes.wstring_at address,size ctypes.wstring_at


.. function:: memoryview_at(address, size, readonly=False)

This function returns a :class:`memoryview` object that references the
memory starting at *address* up to (but not including) *address +
size*. If *readonly* is set to a truthy value then the
:class:`!memoryview` object is immutable.

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(address))``

.. audit-event:: ctypes.memoryview_at address,size,readonly ctypes.buffer_at

.. versionadded:: 3.13


.. _ctypes-data-types:

Data types
Expand Down
10 changes: 10 additions & 0 deletions Doc/whatsnew/3.13.rst
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,16 @@ copy
any user classes which define the :meth:`!__replace__` method.
(Contributed by Serhiy Storchaka in :gh:`108751`.)

ctypes
------

* :func:`ctypes.memoryview_at` now exists to create a
:class:`memoryview` object that refers to the supplied pointer and
length. Works just like :func:`ctypes.string_at` except it avoids a
buffer copy. Useful when implementing callback functions in Python
that are passed dynamically-sized buffers.
(Contributed by Rian Hunter in :gh:`112018`.)

dbm
---

Expand Down
8 changes: 8 additions & 0 deletions Lib/ctypes/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -538,6 +538,14 @@ def wstring_at(ptr, size=-1):
Return the string at addr."""
return _wstring_at(ptr, size)

from _ctypes import _memoryview_at_addr

_memoryview_at = PYFUNCTYPE(py_object, c_void_p, c_ssize_t, c_int)(_memoryview_at_addr)
def memoryview_at(ptr, size, readonly=False):
"""memoryview_at(addr, size[, readonly]) -> memoryview

Return a memoryview representing the memory at addr."""
return _memoryview_at(ptr, size, bool(readonly))

if _os.name == "nt": # COM stuff
def DllGetClassObject(rclsid, riid, ppv):
Expand Down
20 changes: 20 additions & 0 deletions Lib/test/test_ctypes/test_memfunctions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
create_string_buffer, string_at,
create_unicode_buffer, wstring_at,
memmove, memset,
memoryview_at, c_void_p,
c_char_p, c_byte, c_ubyte, c_wchar)


Expand Down Expand Up @@ -77,6 +78,25 @@ def test_wstring_at(self):
self.assertEqual(wstring_at(a, 16), "Hello, World\0\0\0\0")
self.assertEqual(wstring_at(a, 0), "")

def test_memoryview_at(self):
b = (c_byte * 10)()

foreign_ptr = cast(b, c_void_p)
foreign_ptr_size = len(b)

# memoryview_at() is normally used with pointers given to us
# by C APIs. It's an efficient way to get a buffer
# representing a dynamically-sized memory region without having
# to create an array type first.
v = memoryview_at(foreign_ptr, foreign_ptr_size)

# test that writes to source buffer get reflected in memoryview
b[:] = b"0123456789"
self.assertEqual(bytes(v), b"0123456789")

# test that writes to memoryview get reflected in source buffer
v[:] = b"9876543210"
self.assertEqual(bytes(b), b"9876543210")

if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
:func:`ctypes.memoryview_at` now exists to create a
:class:`memoryview` object that refers to the supplied pointer and
length. Works just like :func:`ctypes.string_at` except it avoids a
buffer copy. Useful when implementing callback functions in Python
that are passed dynamically-sized buffers.
12 changes: 12 additions & 0 deletions Modules/_ctypes/_ctypes.c
Original file line number Diff line number Diff line change
Expand Up @@ -5642,6 +5642,17 @@ wstring_at(const wchar_t *ptr, int size)
return PyUnicode_FromWideChar(ptr, ssize);
}

static PyObject *
memoryview_at(char *ptr, Py_ssize_t size, int readonly)
{
if (PySys_Audit("ctypes.memoryview_at", "nni", (Py_ssize_t)ptr, size,
readonly) < 0) {
return NULL;
}

return PyMemoryView_FromMemory(ptr, size,
readonly ? PyBUF_READ : PyBUF_WRITE);
}

static struct PyModuleDef _ctypesmodule = {
PyModuleDef_HEAD_INIT,
Expand Down Expand Up @@ -5777,6 +5788,7 @@ _ctypes_add_objects(PyObject *mod)
MOD_ADD("_string_at_addr", PyLong_FromVoidPtr(string_at));
MOD_ADD("_cast_addr", PyLong_FromVoidPtr(cast));
MOD_ADD("_wstring_at_addr", PyLong_FromVoidPtr(wstring_at));
MOD_ADD("_memoryview_at_addr", PyLong_FromVoidPtr(memoryview_at));

/* If RTLD_LOCAL is not defined (Windows!), set it to zero. */
#if !HAVE_DECL_RTLD_LOCAL
Expand Down