Created
September 20, 2025 14:10
-
-
Save ynkdir/0272e48d344affb81fc1e0864f46860d to your computer and use it in GitHub Desktop.
How to get pointer of memoryview (and how to break python object)
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
| # How to get pointer of memoryview (and how to break python object) | |
| from ctypes import * | |
| PyBUF_FULL_RO = 0x0100 | 0x0010 | 0x0008 | 0x0004 | |
| class Py_buffer(Structure): | |
| _fields_ = [ | |
| ("buf", c_void_p), | |
| ("obj", c_void_p), | |
| ("len", c_ssize_t), | |
| ("itemsize", c_ssize_t), | |
| ("readonly", c_int), | |
| ("ndim", c_int), | |
| ("format", c_char_p), | |
| ("shape", POINTER(c_ssize_t)), | |
| ("strides", POINTER(c_ssize_t)), | |
| ("suboffsets", POINTER(c_ssize_t)), | |
| ("internal", c_void_p), | |
| ] | |
| PyObject_GetBuffer = pythonapi.PyObject_GetBuffer | |
| PyObject_GetBuffer.argtypes = [py_object, POINTER(Py_buffer), c_int] | |
| PyObject_GetBuffer.restype = c_int | |
| PyBuffer_GetPointer = pythonapi.PyBuffer_GetPointer | |
| PyBuffer_GetPointer.argtypes = [POINTER(Py_buffer), POINTER(c_ssize_t)] | |
| PyBuffer_GetPointer.restype = c_void_p | |
| PyBuffer_Release = pythonapi.PyBuffer_Release | |
| PyBuffer_Release.argtypes = [POINTER(Py_buffer)] | |
| PyBuffer_Release.restype = None | |
| def memoryview_pointer(obj): | |
| buf = Py_buffer() | |
| PyObject_GetBuffer(obj, buf, PyBUF_FULL_RO) | |
| try: | |
| return PyBuffer_GetPointer(buf, c_ssize_t(0)) | |
| finally: | |
| PyBuffer_Release(buf) | |
| obj = b"hello" | |
| p = memoryview_pointer(obj) | |
| o = c_byte.from_address(p) | |
| o.value = 32 | |
| print(obj) # => b" ello" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment