简体   繁体   中英

Writing to particular address in memory in python

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.

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.

Python itself does not include any facilities to allow the programmer direct access to memory. This means that sadly (or happily, depending on your outlook) the answer to your question is "no".

You can use ctypes to modify any user-space memory location, given the memory address.

For example numpy array exposes raw address of array buffer, so you can access/modify the value like this:

import numpy as np
import ctypes

a=np.random.rand(2,3)
addr=a.__array_interface__['data'][0]
p=ctypes.c_void_p(addr)
pf=ctypes.cast(p, ctypes.POINTER(ctypes.c_double))
assert pf[0] == a[0,0]
assert pf[1] == a[0,1]
assert pf[3] == a[1,0]

but you cannot easily apply this trick to normal python variable like int, for id() returns the start address of the python object, not the exact location where the value is stored, check this:

from ctypes import *
a=123456
p=cast(c_void_p(id(a)), POINTER(c_int))
print(p[:10])

from the result we can see the value is actually at offset 6*4=24

[1, 0, -1792371528, 127, 1, 0, 123456, 1, 1, 0]

I can't advise how but I do know (one) why. Direct writing to registers allows one to set up a particular microcontroller. For example, configuring ports or peripherals. This is normally done in C (closer to hardware) but it would be a nice feature if you wanted to use Python for other reasons.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM