【问题标题】:Python ctypes pointer and allocated memoryPython ctypes 指针和分配的内存
【发布时间】:2021-06-29 08:07:21
【问题描述】:

假设我想使用 ctypesPython 将指向 int 的指针传递给 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 变量引用的。但我不确定他们是否在第二个。没有引用这些内容的变量。可以垃圾回收吗?还是指针指向它的唯一事实使内容安全分配?

【问题讨论】:

    标签: python ctypes


    【解决方案1】:

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

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

    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
    

    也就是说,在第二个版本中也不会有悬空指针,它可以保存使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 2013-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多