简体   繁体   English

在python中写入内存中的特定地址

[英]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.我知道 python 是一种高级语言,它自己管理内存分配等。与 c、c++ 等其他语言不同,它不需要担心太多。

but is there a way through will we can write some value in a particular memory address in python但是有没有办法通过我们可以在python的特定内存地址中写入一些值

i know about id() which if hex type casted can give hexadecimal location but how can we write at a location.我知道 id() 如果十六进制类型转换可以给出十六进制位置,但我们如何在一个位置写入。

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++ . Python 本身经过构建,因此很容易通过 C 或 C++ 扩展它 It's even easier doing it via Cython .通过Cython更容易做到。

The following sketches how to build a Python-callable function taking integers p and v .下面概述了如何使用整数pv构建 Python 可调用函数。 It will write the value v to the memory address whose numeric address is p .它将值v写入数字地址为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:创建一个文件modify.h ,内容为:

void modify(int p, int v);

Create a file modify.c , with the content:创建一个文件modify.c ,内容为:

#include "modify.h"

void modify(int p, int v)
{
    *(int *)(p) = v;
}

Create a file modify.pyx , with the content:创建一个文件modify.pyx ,内容为:

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:最后,创建setup.py ,内容如下:

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. Python 本身不包含任何允许程序员直接访问内存的设施。 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.给定内存地址,您可以使用 ctypes 修改任何用户空间内存位置。

For example numpy array exposes raw address of array buffer, so you can access/modify the value like this:例如 numpy 数组公开数组缓冲区的原始地址,因此您可以像这样访问/修改值:

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:但是你不能轻易地将这个技巧应用到像 int 这样的普通 python 变量,因为 id() 返回 python 对象的起始地址,而不是存储值的确切位置,检查这个:

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从结果中我们可以看到该值实际上在偏移量 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.这通常是在 C 中完成的(更接近硬件),但如果您出于其他原因想使用 Python,这将是一个很好的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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