[英]ctypes memory management: how and when free the allocated resources?
I'm writing a small wrapper for a C library in Python with Ctypes, and I don't know if the structures allocated from Python will be automatically freed when they're out of scope. 我正在用Ctypes在Python中为C库编写一个小包装器,我不知道从Python分配的结构是否会在超出范围时自动释放。
Example: 例:
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()
Will that point still be "alive" after foo returns? 在foo返回后,这一点仍然“活着”吗? Do I have to call
clib.free(pointer(p))
? 我是否必须调用
clib.free(pointer(p))
? or does ctypes provide a function to free memory allocated for C structures? 或者ctypes是否提供释放为C结构分配的内存的函数?
In this case your MyPoint
instance is a Python object allocated on the Python heap, so there should be no need to treat it differently from any other Python object. 在这种情况下,您的
MyPoint
实例是在Python堆上分配的Python对象,因此不需要将其与任何其他Python对象区别对待。 If, on the other hand, you got the MyPoint
instance by calling say allocate_point()
in mylib.so
, then you would need to free it using whatever function is provided for doing so, eg free_point(p)
in mylib.so
. 另一方面,如果你通过在
mylib.so
调用say allocate_point()
得到MyPoint
实例,那么你需要使用为此提供的任何函数释放它,例如mylib.so
free_point(p)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.