Python ctypes 指针和分配的内存

标签 python ctypes

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

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 变量引用指向的内容。但我不确定他们是否属于第二个。没有变量引用这些内容。可以垃圾收集吗?或者仅仅因为指针指向它就可以安全地分配内容?

最佳答案

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

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

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

这意味着,在第二个版本中也不会有悬空指针,并且可以保存使用。

关于Python ctypes 指针和分配的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68174831/

相关文章:

python - Ctypes 偏移到缓冲区中

python - Lazarus 库在 OSX 的 Python 中使用 ctypes

python - 在Python中导入深度嵌套的模块

python - 在 Pandas 数据框中选择不同的列

python - 类成员还是实例属性?

python - 更改按钮文本消息框

c++ - Ctypes "symbol not found"用于 OSX 中的动态库

python - 在 python 中打印两个骰子可能掷出的二维列表

Python:使用 for 循环创建嵌套的浮点列表

Python:内存管理优化不一致?