ctypes free memory which is allocated in C DLL

Ken Chen zlchen.ken at gmail.com
Sat Oct 27 11:40:49 EDT 2012


On Saturday, October 27, 2012 10:56:54 PM UTC+8, Chris Angelico wrote:
> On Sun, Oct 28, 2012 at 1:42 AM,  <zlchen.ken at gmail.com> wrote:
> 
> > Hi Guys,
> 
> >
> 
> > I have a DLL which written in C language, one of the function is to allocate a structure, fill the members and then return the pointer of the structure.
> 
> >
> 
> > After Python called this function, and done with the returned structure, I would like to free the returned structure. How can I achieve this ? Basically, I tried that I wrote a corresponding free interface in the DLL, it works, but calling the libc.free in Python doesn't work.
> 
> 
> 
> As a general rule, you should always match your allocs and frees. Use
> 
> the same library to free the memory as was used to allocate it.
> 
> Nothing else is safe. If your DLL exposes an API that allocates
> 
> memory, your DLL should expose a corresponding API to free it. So what
> 
> you have is the best way :)
> 
> 
> 
> ChrisA

Thanks a lot, Chris!
Yes, I agree writing a corresponding API to free the memory is the best practice and best bet.
Sometimes, the third party API may not provide that.

After digging the Python manual again and again.
I finally figure out why windll.msvcrt.free is failing.

As the manual stated below, the DLL is using another version of msvcrt lib which is different than the builtin windll.msvcrt. After I explicitly load the msvcrt which built the DLL, things are getting function now.

"ctypes.util.find_msvcrt() 
Windows only: return the filename of the VC runtype library used by Python, and by the extension modules. If the name of the library cannot be determined, None is returned.

If you need to free memory, for example, allocated by an extension module with a call to the free(void *), it is important that you use the function in the same library that allocated the memory."




More information about the Python-list mailing list