Python ctypes 指针和分配的内存

Python ctypes pointer and allocated memory

假设我想将指向 int 的指针传递给 Python 中的 C 函数,使用ctypes:

from ctypes import *
lib = CDLL("./myLib.so")
i = c_int(50)
pi = pointer(i)
lib.myfunc(pi)

这段代码没问题。但是假设我改为这样做:

from ctypes import *
lib = CDLL("./myLib.so")
pi = pointer(c_int(50))
lib.myfunc(pi)

关于垃圾收集器会发生什么?在第一个示例中,指向的内容是通过 i 变量引用的。但我不确定他们是否在第二个。没有引用这些内容的变量。它可以被垃圾收集吗?或者指针指向它的唯一事实使内容安全分配?

创建 pointer 对象时,它会保留原始对象的引用,从而防止原始对象被破坏。

您可以使用以下代码验证此行为:

from ctypes import *
import sys
i = c_int(50)
print(sys.getrefcount(i)) # => 2 - a reference from i and one as argument of sys.getfrefcount
pi = pointer(i)
print(sys.getrefcount(i)) # => 3 - additional reference is saved in pi
del pi
print(sys.getrefcount(i)) # => 2 again - the reference from pi was cleared

也就是说,同样在第二个版本中,将没有悬挂指针,可以节省使用。