Writing to particular address in memory in python
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.