In Python, how to explicitly free the non-trivial memory (not int/char/ etc) returned by C module ?
Say C interface is like as below:
____________________
struct Dummy
{
int a;
int b;
}:
struct Dummy* allocate_dummy(int a, int b)
{
struct Dummy * dummy = (struct Dummy*) malloc (sizeof(struct Dummy));
dummy->a = a;
dummy->b = b;
return dummy;
}
____________________
Python code:
class Dummy(Structure):
_fields__ = [('a', c_int), ('b', c_int)]
dummy_dll = CDLL('dummy.dll')
dummy_dll.allocate_dummy.argtypes = [c_int, c_int]
dummy_dll.allcate_dummy.restypes = POINTER(Dummy)
res = dummy_dll.allocate_dummy(1, 2)
...
____________________
In order to free "res", we can do:
1) Write a "void free_dummy(struct Dummy* pd)" to do this (Basically this is the best practice and the best way if possible)
2) Call msvcrt.free to free the memory. Tricks, please REMEMBER TO use the same MS C RUNTIME library as the allocated one to free the memory, otherwise, usually you got access violation issue.
Basically, cdll.msvcrt.free is not what you need. For example, I build a dll by using Visual Studio 2012 Express, then the right dll which fress the allocated memory will be something like:
msvcrt = CDLL('C:\\Program Files (x86)\\Microsoft Visual Studio 11.0\\VC\\redist\\x64\Microsoft.VC110.CRT\\msvcr110.dll')
Same issue may happen in Linux env.