I know python is a high level language and manages the memory allocation etc. on its own user/developer doesn't need to worry much unlike other languages like c, c++ etc.
but is there a way through will we can write some value in a particular memory address in python
i know about id() which if hex type casted can give hexadecimal location but how can we write at a location.
Writing a Memory-Mapped File With Python's mmap. Memory mapping is most useful for reading files, but you can also use it to write files.
It can be done in these ways:Using id() function. Using addressof() function. Using hex() function.
On UNIX, you can try to open() the /dev/mem device to access the physical memory, and then use the seek() method of the file object set the file pointer to the right location. Then use the write() method to change the value. Don't forget to encode the number as a raw string!
In Python, we cannot directly access memory. However, we have ctypes module to get value from memory address. Caution: Make sure while using ctypes.
To begin with, as noted in the comments, it's quite a question why you would want to do such a thing at all. You should consider carefully whether there is any alternative.
Having said that, it is quite easy to do so via extensions. Python itself is built so that it is easy to extend it via C or C++. It's even easier doing it via Cython.
The following sketches how to build a Python-callable function taking integers p
and v
. It will write the value v
to the memory address whose numeric address is p
.
Note Once again, note, this is a technical answer only. The entire operation, and parts of it, are questionable, and you should consider what you're trying to achieve.
Create a file modify.h
, with the content:
void modify(int p, int v);
Create a file modify.c
, with the content:
#include "modify.h"
void modify(int p, int v)
{
*(int *)(p) = v;
}
Create a file modify.pyx
, with the content:
cdef extern from "modify.h"
void modify(int p, int v)
def py_modify(p, v):
modify(p, v)
Finally, create setup.py
, with the content:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [Extension(
name="modify",
sources=["modify.pyx", "modify.c"])]
setup(
name = 'modify',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules,
# ext_modules = cythonize(ext_modules) ? not in 0.14.1
# version=
# description=
# author=
# author_email=
)
I hope you use this answer for learning purposes only.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With