首页 > 解决方案 > 有没有办法通过 Python 中的 id 获取对象的大小?

问题描述

我需要编写一个通过 id 返回对象的函数。我不能使用ctypes.cast、_ctypes、gc、locals、globals等,建议使用struct和ctypes。例如,对于 int 类型的对象,我编写以下内容:

struct.unpack ("LLli", ctypes.string_at (id_of_object, 28))

如果我知道对象的大小是 28 字节。但是对象可以是任意大小。例如,对于 object = 2**30,大小将为 32 字节。我可以通过它的 id 以某种方式获取对象本身的大小吗?还是我需要在此任务中使用其他一些方法?

标签: pythonstructctypes

解决方案


任何对象都以引用计数和引用类型开始。我的问题可以这样解决:首先,使用 ctypes.string_at,我们得到一个类型的引用,它将是元组中的第二个:

struct.unpack ("LL", ctypes.string_at (object_id, 16))

然后,例如,在 int 类型的情况下,我们得到对象的“块”数,它将是元组中的第三个:

info = struct.unpack ("LLl", ctypes.string_at (object_id, 24))

最后,我们得到整数:

num_of_pieces = abs (info [2])
size_of_obj = 24 + 4 * num_of_pieces
type_string = "i" * num_of_pieces
number = struct.unpack ("LLl" + type_string, ctypes.string_at (object_id, size_of_obj))
i = 0
res = 0
for n in number [3:]:
    res + = n * (2 ** 30) ** i
    i + = 1
return res if info [2]> 0 else -res

对于其他类型,一切都会有所不同,我不得不分别处理每种情况。


推荐阅读