Releasing malloc'd memory using ctypes?

Chris Mellon arkanes at gmail.com
Mon Dec 24 11:03:55 EST 2007


On Dec 23, 2007 12:36 PM,  <skip at pobox.com> wrote:
> I am starting to experiment with ctypes.  I have a function which returns a
> pointer to a struct allocated in heap memory.  There is a corresponding free
> function for that sort of struct, e.g.:
>
>     from ctypes import *
>
>     cdll.LoadLibrary("libthing.so")
>     c_thing = CDLL("libthing.so")
>
>     class THING(Structure):
>         _fields_ = [("name", c_char_p),
>                     ("value", c_int)]
>
>     get_thing = c_thing.get_thing
>     get_thing.restype = POINTER(THING)
>     free_thing = c_thing.free_thing
>
> So I call get_thing() and get back this ctypes wrapper for a pointer to a
> thing.  I can extract the name and value elements from the thing instance
> just fine:
>
>     thing_p = get_thing()
>     thing = thing_p.contents
>     print thing.name, "=", thing.value
>
> Now I need to call free_thing.  What do I pass it?  thing_p?  Some attribute
> of thing_p?  Something else altogether?  The ctypes module docs seem to be
> strangely silent on the question of freeing heap memory which you've
> received from the underlying library's functions.
>

You do it just like you'd do in C, and pass the return value of
get_thing. Make sure that you declare free_thing as taking a pointer
so ctypes knows to do the right thing.



More information about the Python-list mailing list