HYR*_*YRY 163
如果对象仍在那里,可以通过以下方式完成ctypes
:
import ctypes
a = "hello world"
print ctypes.cast(id(a), ctypes.py_object).value
Run Code Online (Sandbox Code Playgroud)
输出:
hello world
Run Code Online (Sandbox Code Playgroud)
如果您不知道对象是否仍然存在,这是未定义行为的配方和奇怪的崩溃或更糟,所以要小心.
Man*_*ron 36
您可以使用gc模块获取Python垃圾收集器当前跟踪的所有对象.
import gc
def objects_by_id(id_):
for obj in gc.get_objects():
if id(obj) == id_:
return obj
raise Exception("No found")
Run Code Online (Sandbox Code Playgroud)
cha*_*aos 35
Short answer, you can't.
Long answer, you can maintain a dict for mapping IDs to objects, or look the ID up by exhaustive search of gc.get_objects()
, but this will create one of two problems: either the dict's reference will keep the object alive and prevent GC, or (if it's a WeakValue dict or you use gc.get_objects()
) the ID may be deallocated and reused for a completely different object.
Basically, if you're trying to do this, you probably need to do something differently.
只需提及此模块即可完成.Bill Bumgarner编写的这段代码包含一个C扩展,可以在不存在每个对象的情况下执行您想要的操作.
该函数的代码非常简单.每个Python对象是用C由一个指向表示一个PyObject
结构.因为id(x)
它只是这个结构的内存地址,所以我们可以通过将其x
视为指向a的指针来检索Python对象PyObject
,然后调用Py_INCREF
告诉垃圾收集器我们正在创建对该对象的新引用.
static PyObject *
di_di(PyObject *self, PyObject *args)
{
PyObject *obj;
if (!PyArg_ParseTuple(args, "l:di", &obj))
return NULL;
Py_INCREF(obj);
return obj;
}
Run Code Online (Sandbox Code Playgroud)
如果原始对象不再存在,则结果未定义.它可能会崩溃,但它也可能返回对新对象的引用,该对象在内存中占用旧对象的位置.
归档时间: |
|
查看次数: |
66609 次 |
最近记录: |