如何在Python中使用C API获取对象ID?

How to get object ID using C API in Python?

我想知道 - 是否有使用 CPython 的 C API 获取对象 ID 的规范方法?

对象id只是指针值:

PyObject *some_py_object = ...;
intptr_t id = (intptr_t)some_py_object;

或者如果你 want it as a Python object:

PyLong_FromVoidPtr(some_py_object)

这是 CPython 特定的实现细节。如果您担心与其他版本 Python 的兼容性(例如 PyPy 通过其 C API 兼容层),您可能应该导入 builtins,获取属性 id 并调用它,使用正常的 C-API 机制来做到这一点。