Created
January 24, 2026 16:37
-
-
Save zhangyoufu/a220869eb0f40a09e416d8dd71e5889f to your computer and use it in GitHub Desktop.
CPython: fake readwrite buffer from readonly buffer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import ctypes | |
| import mmap | |
| # https://stackoverflow.com/a/34096544 | |
| def fake_readwrite_buffer(obj: object) -> memoryview: | |
| address = ctypes.c_void_p() | |
| length = ctypes.c_ssize_t() | |
| ctypes.pythonapi.PyObject_AsReadBuffer(ctypes.py_object(obj), ctypes.byref(address), ctypes.byref(length)) | |
| return ctypes.memoryview_at(address.value, length, readonly=False) | |
| mm = mmap.mmap(-1, 4096, prot=mmap.PROT_READ) | |
| mv = fake_readwrite_buffer(mm) | |
| ctypes.c_int.from_buffer(mv, 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment