ctypes & allocated memory

Barry barry at barrys-emacs.org
Sun Jun 7 16:25:27 EDT 2020



> On 7 Jun 2020, at 14:23, Miki Tebeka <miki.tebeka at gmail.com> wrote:
> 
> Hi,
> 
> Does ctypes, when using restype, frees allocated memory?
> 
> For example, will the memory allocated by "strdup" be freed after the "del" statement? If not, how can I free it?

See https://linux.die.net/man/3/strdup that tells you to use free() to delete memory allocated by strdup.

You must remember the result of strdup and free it at an appropriate time.

Barry

> 
> ---
> import ctypes
> 
> libc = ctypes.cdll.LoadLibrary('libc.so.6')
> strdup = libc.strdup
> strdup.argtypes = [ctypes.c_char_p]
> strdup.restype = ctypes.c_char_p
> 
> out = strdup(b'hello').decode('utf-8')
> print(out)  # hello
> del out
> ---
> 
> Thanks,
> Miki
> -- 
> https://mail.python.org/mailman/listinfo/python-list
> 


More information about the Python-list mailing list