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

编程入门 行业动态 更新时间:2024-10-23 13:26:39
本文介绍了在python中写入内存中的特定地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我知道 python 是一种高级语言,可以自行管理内存分配等.与 c、c++ 等其他语言不同,开发人员无需担心太多

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的特定内存地址中写入一些值

but is there a way through will we can write some value in a particular memory address in python

我知道 id() 如果十六进制类型转换可以给出十六进制位置,但我们如何在一个位置写入.

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.

话虽如此,通过扩展很容易做到这一点.Python 本身经过构建,因此很容易通过 C 或 C++ 扩展它.通过 Cython 更容易做到这一点.

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.

下面概述了如何使用整数 p 和 v 构建 Python 可调用函数.它将值v 写入数值地址为p 的内存地址.

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.

创建一个文件modify.h,内容为:

Create a file modify.h, with the content:

void modify(int p, int v);

创建一个文件modify.c,内容为:

Create a file modify.c, with the content:

#include "modify.h" void modify(int p, int v) { *(int *)(p) = v; }

创建一个文件modify.pyx,内容为:

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)

最后,创建setup.py,内容如下:

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中写入内存中的特定地址

本文发布于:2023-08-01 04:28:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1265213.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:内存   地址   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!