Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Revert to calling through ctypes to get c_void_p conversion seman…
…tics. Improve tests and docs.
  • Loading branch information
encukou committed Nov 29, 2024
commit 3a6b559e08a2d0c53b93d5fda58dd5ff76e3a0d3
19 changes: 10 additions & 9 deletions Doc/library/ctypes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2164,21 +2164,22 @@ Utility functions
.. audit-event:: ctypes.wstring_at ptr,size ctypes.wstring_at


.. function:: memoryview_at(address, size, readonly=False)
.. function:: memoryview_at(ptr, 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 returns a :class:`memoryview` object of length *size* that
references the memory starting at *void \*ptr*, .
If *readonly* is true 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))``
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 integer, *ptr* can also
be given as a :class:`ctypes.POINTER` or a :func:`~ctypes.byref` object.)

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

.. versionadded:: 3.13
.. versionadded:: next

Comment thread
rianhunter marked this conversation as resolved.

.. _ctypes-data-types:
Expand Down
9 changes: 8 additions & 1 deletion Lib/ctypes/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
from _ctypes import RTLD_LOCAL, RTLD_GLOBAL
from _ctypes import ArgumentError
from _ctypes import SIZEOF_TIME_T
from _ctypes import memoryview_at

from struct import calcsize as _calcsize

Expand Down Expand Up @@ -525,6 +524,7 @@ def WinError(code=None, descr=None):
# functions

from _ctypes import _memmove_addr, _memset_addr, _string_at_addr, _cast_addr
from _ctypes import _memoryview_at_addr
Comment thread
picnixz marked this conversation as resolved.

## void *memmove(void *, const void *, size_t);
memmove = CFUNCTYPE(c_void_p, c_void_p, c_void_p, c_size_t)(_memmove_addr)
Expand All @@ -550,6 +550,13 @@ def string_at(ptr, size=-1):
Return the byte string at void *ptr."""
return _string_at(ptr, size)

_memoryview_at = PYFUNCTYPE(py_object, c_void_p, c_int, c_int)(_memoryview_at_addr)
def memoryview_at(ptr, size, readonly=False):
"""memoryview_at(ptr[, size]) -> memoryview
Comment thread
encukou marked this conversation as resolved.
Outdated

Return a memoryview representing the memory at addr."""
Comment thread
encukou marked this conversation as resolved.
Outdated
return _memoryview_at(ptr, size, bool(readonly))

try:
from _ctypes import _wstring_at_addr
except ImportError:
Expand Down
40 changes: 25 additions & 15 deletions Lib/test/test_ctypes/test_memfunctions.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
create_unicode_buffer, wstring_at,
memmove, memset,
memoryview_at, c_void_p,
c_char_p, c_byte, c_ubyte, c_wchar)
c_char_p, c_byte, c_ubyte, c_wchar,
addressof, byref)


class MemFunctionsTest(unittest.TestCase):
Expand Down Expand Up @@ -83,20 +84,29 @@ def test_memoryview_at(self):

foreign_ptr = cast(b, c_void_p)
Comment thread
ZeroIntensity marked this conversation as resolved.
Outdated
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")
for foreign_ptr in (
b,
cast(b, c_void_p),
byref(b),
addressof(b)
):
with self.subTest(foreign_ptr=type(foreign_ptr).__name__):
v = memoryview_at(foreign_ptr, foreign_ptr_size)
self.assertIsInstance(v, memoryview)

# 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")

with self.assertRaises(ValueError):
memoryview_at(foreign_ptr, -1)

v0 = memoryview_at(foreign_ptr, 0)
self.assertEqual(bytes(v0), b'')

if __name__ == "__main__":
unittest.main()
38 changes: 7 additions & 31 deletions Modules/_ctypes/_ctypes.c
Original file line number Diff line number Diff line change
Expand Up @@ -5741,34 +5741,18 @@ wstring_at(const wchar_t *ptr, int size)
return PyUnicode_FromWideChar(ptr, ssize);
}

/*[clinic input]
_ctypes.memoryview_at

obj: object
/
size: Py_ssize_t
readonly: bool = False

Return a memoryview representing the memory at addr.
[clinic start generated code]*/

static PyObject *
_ctypes_memoryview_at_impl(PyObject *module, PyObject *obj, Py_ssize_t size,
int readonly)
/*[clinic end generated code: output=c89fdda64bd9901d input=c960c5a2b3ccb9fb]*/
memoryview_at(void *ptr, int size, int readonly)
{
ctypes_state *st = get_module_state(module);
if (!CDataObject_Check(st, obj)) {
PyErr_SetString(PyExc_TypeError, "invalid type");
Py_ssize_t ssize = size;
Comment thread
encukou marked this conversation as resolved.
Outdated
if (PySys_Audit("ctypes.memoryview_at", "nni",
(Py_ssize_t)ptr, ssize, readonly) < 0) {
return NULL;
}
void *ptr = ((CDataObject *)obj)->b_ptr;

if (PySys_Audit("ctypes.memoryview_at", "nni", (Py_ssize_t)ptr, size,
readonly) < 0) {
if (ssize < 0) {
PyErr_SetString(PyExc_ValueError, "size must not be negative");
return NULL;
}

return PyMemoryView_FromMemory(ptr, size,
readonly ? PyBUF_READ : PyBUF_WRITE);
}
Expand Down Expand Up @@ -5900,6 +5884,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 All @@ -5920,12 +5905,6 @@ _ctypes_add_objects(PyObject *mod)
#undef MOD_ADD
}

// Most ctypes methods are defined in callproc.c.
// Here is the rest.
static PyMethodDef module_methods[] = {
_CTYPES_MEMORYVIEW_AT_METHODDEF
{NULL, NULL} /* Sentinel */
};

static int
_ctypes_mod_exec(PyObject *mod)
Expand Down Expand Up @@ -5953,9 +5932,6 @@ _ctypes_mod_exec(PyObject *mod)
if (_ctypes_add_objects(mod) < 0) {
return -1;
}
if (PyModule_AddFunctions(mod, module_methods) < 0) {
return -1;
}

return 0;
}
Expand Down
83 changes: 1 addition & 82 deletions Modules/_ctypes/clinic/_ctypes.c.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.