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.
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? Do I have to call clib.free(pointer(p))
? or does ctypes provide a function to free memory allocated for C structures?
As we know, Python uses the dynamic memory allocation which is managed by the Heap data structure. Memory Heap holds the objects and other data structures that will be used in the program. Python memory manager manages the allocation or de-allocation of the heap memory space through the API functions.
ctypes is a foreign function library for Python. It provides C compatible data types, and allows calling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python.
ctypes.py_object is a type. ctypes.py_object * size is a type. ctypes.py_object() is an instance of a type.
Stack is a linear data structure whereas Heap is a hierarchical data structure. Stack memory will never become fragmented whereas Heap memory can become fragmented as blocks of memory are first allocated and then freed. Stack accesses local variables only while Heap allows you to access variables globally.
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. 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, e.g. free_point(p)
in mylib.so
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With