On Sat, 27 Oct 2012 07:42:01 -0700, zlchen.ken wrote: > 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. > > my_dll.return_structure_ptr.restypes = POINTER(Dummy) res_ptr = > my_dll.return_structure_ptr() windll.msvcrt.free(res_ptr) <==== doesn't > work, memory violation my_dll.free_dummy_struture(res_ptr) <== This > works.
On Windows, a process may have multiple versions of the MSVCRT DLL (which provides malloc/free). If an executable or DLL is linked against multiple DLLs, each DLL could be using a different version of MSVCRT. Different versions of MSVCRT may have separate heaps, so anything which is allocated with malloc() (or calloc() or realloc()) from a specific version of MSVCRT must be passed to free() from the same version of MSVCRT. windll.msvcrt refers to the version of MSVCRT against which the Python DLL is linked, which isn't necessarily the version against which my_dll is linked. If a function in a DLL returns a pointer to memory which it allocated with malloc(), that DLL must also provide a function which can be used to free that memory. It can't leave it to the application (or higher-level DLL) to call free(), because the application may not be using the same version of MSVCRT as the DLL. -- http://mail.python.org/mailman/listinfo/python-list