方法一:
from _ctypes import PyObj_FromPtr
# 通过id获取该地址的值
def get_value_by_id(obj_id):
return PyObj_FromPtr(obj_id)
value='hello world' #定义一个字符串变量
address=id(value) #获取value的地址,赋给address
get_value = get_value_by_id(address)
print(get_value)
# hello world
方法二:
import ctypes
def get_value_by_id(obj_id):
return ctypes.cast(obj_id, ctypes.py_object).value
value='hello world' #定义一个字符串变量
address=id(value) #获取value的地址,赋给address
get_value = get_value_by_id(address)
print(get_value)
# hello world
参考链接:
Python如何通过变量ID得到变量的值
本文介绍了Python中通过变量的ID获取其值的两种方法:一是使用`ctypes`库的`PyObj_FromPtr`函数,二是直接利用`ctypes.cast`结合`py_object`和`value`属性。这两种方法都能实现从内存地址获取变量的值。
3712

被折叠的 条评论
为什么被折叠?



