8

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.

pkm
  • 2,683
  • 2
  • 29
  • 44
  • You can't write on a hard code memory location even in C, unless you are working on some systems where you have absolute access to memory. http://stackoverflow.com/questions/11207783/read-and-write-to-a-memory-location – niyasc Aug 01 '16 at 10:33
  • Not a duplicate, but see the discussion here: http://stackoverflow.com/questions/8250625/access-memory-address-in-python – cdarke Aug 01 '16 at 10:33

4 Answers4

3

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.

Andrejs Cainikovs
  • 27,428
  • 2
  • 75
  • 95
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
  • Is this solution applicable for following usage: I want to code a GUI with some buttons acting on data, create an .exe program and allows people to install it on their computers. So I need to be able, on starting, that the program recall former data saved "somewhere" and reuse it each time it is started – totalMongot Jan 06 '22 at 17:31
2

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]
TingQian LI
  • 660
  • 8
  • 13
0

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".

holdenweb
  • 33,305
  • 7
  • 57
  • 77
  • AFAIK, "Python itself" doesn't allow GPU manipulation, or socket messaging. It merely allows doing so through extensions and libraries. So the answer might be strictly correct, but you could apply its rationale to several other questions where Python is used in practice. – Ami Tavory Aug 01 '16 at 11:34
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.