views:

269

answers:

1

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?

+2  A: 

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.

Vinay Sajip
So I deduce that if some C function called with a pointer to "p" as argument keeps a copy of it somewhere (a global variable, for example), that reference would become invalid after the Python GC claims it, right?
fortran
That's right, it would become a dangling pointer.
Vinay Sajip