python - 有没有办法通过 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 以某种方式获取对象本身的大小吗?还是我需要在此任务中使用其他一些方法?
解决方案
任何对象都以引用计数和引用类型开始。我的问题可以这样解决:首先,使用 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
对于其他类型,一切都会有所不同,我不得不分别处理每种情况。
推荐阅读
- c++ - 将流运算符与模板类一起使用
- c++ - 使用zedboard编译错误
- angular - 选择数据时,视图中的详细信息会被破坏。使用角 6
- vb.net - AppHangB1 试图让 Outlook.Explorer 脱颖而出
- c - 为 PostgreSQL 9.6 编译 C 函数时出错
- symfony - 无法使用 sonataClassificationBundle 更新数据库 symfony 4
- kubernetes - 如何在 pod 中挂载持久卷?
- java - Spring Boot 2 和 QueryDSL 集成不起作用?
- .net-core - VSTS上的Nuget还原版本冲突构建错误
- c# - WebBrowser 未触发事件 DocumentCompleted