python - pythonapi.PyObject_GC_UnTrack 返回什么?

标签 python c memory-management garbage-collection ctypes

假设我定义了一个容器对象(在我们的例子中是列表),由 CPython 的 GC 自动跟踪。然后决定使用 ctypes 的 pythonapi 函数取消跟踪它。文档 says PyObject_GC_UnTrack 返回 void,但是,当通过 pythonapi 调用它时,它返回一个整数,该整数不是未跟踪对象的内存地址,也不是它的指针。

>>>import ctypes
>>>from ctypes import pythonapi, py_object
>>>import gc
>>>a = [1,2,3,4,5]
>>>pythonapi.PyObject_GC_UnTrack(py_object(a))
-396907592
>>>gc.is_tracked(a)
False

最佳答案

来自 ctypes 文档:

ctypes.pythonapi

An instance of PyDLL that exposes Python C API functions as attributes. Note that all these functions are assumed to return C int, which is of course not always the truth, so you have to assign the correct restype attribute to use these functions.

ctypes 假定函数返回 C 整数通常是正确的(不仅仅是特定于 pythonapi)。

>>> pythonapi.PyObject_GC_UnTrack.restype
<class 'ctypes.c_long'>

(在此框上,intlong 相同)。

如果这很重要,你必须自己设置restype:

>>> pythonapi.PyObject_GC_UnTrack.restype = None # which means "void"
>>> a = [1,2,3,4,5]
>>> pythonapi.PyObject_GC_UnTrack(py_object(a))
[no output]

PyObject_GC_UnTrack 返回 void 是真的;只要 ctypes 认为它返回一个 int,ctypes 就会返回垃圾字节。这里来自 Modules/gcmodule.c:

void
PyObject_GC_UnTrack(void *op)
{
    /* Obscure:  the Py_TRASHCAN mechanism requires that we be able to
     * call PyObject_GC_UnTrack twice on an object.
     */
    if (IS_TRACKED(op))
        _PyObject_GC_UNTRACK(op);
}

关于python - pythonapi.PyObject_GC_UnTrack 返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23621212/

相关文章:

C - 随机数生成

c - brk() 上的 Bash 脚本段错误

c - 为什么释放内存会导致段错误?

c - Linux内核中kzalloc_node中的内存节点是什么

python - 在 Pandas 中同时在所有列中使用 apply 函数

python - Postgis - 在插入之前如何检查几何类型

python - 将目录中的所有 JPG 文件复制到 Python 中的另一个目录?

python - 如何拖放带有自定义项目小部件的 QListWidget 项目?

c - 如何通过 ffmpeg 对帧的解码进行基准测试?

objective-c - UIViewController purgeMemoryForReason : Crashing on iOS 5