A view created from an address does not take ownership of the memory behind that address.
Python ctypes.memoryview_at: keep native pointer storage alive
Operation contract
A ctypes buffer owns forty-seven bytes. memoryview_at exposes the same bytes without making a second payload copy; changing the first byte through the owner is visible through the view. The buffer remains alive until the view is released. No external library or untrusted address is used.
Failure boundary
An integer address alone is not a lifetime guarantee. If native code frees or reallocates the storage while Python still reads the view, access can be invalid. The caller must prove the pointer and length are valid for the entire view lifetime. readonly prevents writes through that view but does not freeze memory owned elsewhere.
Working program
import ctypes
receipt_buffer = ctypes.create_string_buffer(b"R" * 47)
address = ctypes.addressof(receipt_buffer)
receipt_view = ctypes.memoryview_at(address, 47, readonly=True)
try:
print("initial", bytes(receipt_view) == b"R" * 47)
receipt_buffer[0] = b"S"
print("owner_change_visible", bytes(receipt_view).startswith(b"S"))
finally:
receipt_view.release()Output
initial True
owner_change_visible TrueCosts and limits
View creation is O(1) and avoids copying the payload. Converting the view to bytes in this small verification allocates and copies forty-seven bytes.
Common Mistakes
- A readonly view does not make other owners unable to write.
- Never construct a view from an unverified integer address or length.
- Keep the native allocation alive until every view is released.
