ctypes free memory which is allocated by C
来源:互联网 发布:2016中美经济数据对比 编辑:程序博客网 时间:2024/06/14 07:14
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.
- ctypes free memory which is allocated by C
- Reference variable is not allocated memory
- #2001 delete[] applied to memory allocated by _tcsdup() (zz)
- 11.Identify the memory component from which memory may be allocated for:
- Displaying Allocated Memory
- Free Linux Memory by Dropping Caches
- 043-OCPThe memory used by Streams will be allocated from the shared pool
- kubernetes free data blocks which is less than minimum required
- TMS320DM642开发之Bug1-Memory map error:READ access by cpu to address 0x1b3f018(Device Config Space)which is not supported in simula
- What is the best free memory leak detector for a C/C++ program and its plug-in DLLs
- What is the best free memory leak detector for a C/C++ program and its plug-in DLLs
- C module with ctypes
- How memory is managed by stack and heap
- In C++, what is a memory arena?
- 39 Which statement about Automatic Memory Management with Oracle 11g is true?
- SQL1220N The database manager shared memory set cannot be allocated.
- Get free memory value
- Linux Memory Usage: free
- 渐渐失去了曾经所拥有的,曾经的人,都渐渐离开了
- 如何在JNI编程中使用logCat
- 二叉查找树的 创建 查找 访问
- TCP三次握手连接及seq和ack号的正确理解
- 删除两个双向链表中相同元素的所有节点
- ctypes free memory which is allocated by C
- 最小 flash I/O单元 与 NAND flash 子页
- Android传感器编程入门(1)
- 算法
- Android开发效率—Eclipse快捷键
- 世界上最遥远的距离,一个在天,一个却深潜海底
- 在Android C/C++层添加LOG调试(LOGI\LOGD\LOGE...)输出支持
- 【CEO来信】稻盛和夫:选择别人没走过的路
- 忘记MySQL root密码的解决方案