ctypes内存管理:如何以及何时释放分配的资源?

for*_*ran 9 c python memory ctypes

我正在用Ctypes在Python中为C库编写一个小包装器,我不知道从Python分配的结构是否会在超出范围时自动释放.

例:

from ctypes import *
mylib = cdll.LoadLibrary("mylib.so")

class MyPoint(Structure):
    _fields_ = [("x", c_int), ("y", c_int)]

def foo():
    p = MyPoint()
    #do something with the point

foo()
Run Code Online (Sandbox Code Playgroud)

在foo返回后,这一点仍然"活着"吗?我必须打电话clib.free(pointer(p))吗?或者ctypes是否提供释放为C结构分配的内存的函数?

Vin*_*jip 5

在本例中,您的MyPoint实例是分配在 Python 堆上的 Python 对象,因此无需将其与任何其他 Python 对象区别对待。另一方面,如果您MyPoint通过调用 say allocate_point()in获得了实例mylib.so,那么您需要使用为此提供的任何函数来释放它,例如free_point(p)in mylib.so