假设我定义了一个容器对象(在我们的例子中是列表),由 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'>
(在此框上,int
与long
相同)。
如果这很重要,你必须自己设置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/