Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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?

like image 276
fortran Avatar asked Sep 21 '09 10:09

fortran


People also ask

How does Python allocate memory?

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.

What is ctypes pointer?

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.

What is ctypes Py_object?

ctypes.py_object is a type. ctypes.py_object * size is a type. ctypes.py_object() is an instance of a type.

What is heap memory and stack memory in Python?

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.


1 Answers

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.

like image 136
Vinay Sajip Avatar answered Sep 18 '22 19:09

Vinay Sajip