ctypes free memory which is allocated by C

本文详细解析了在Python中使用C模块时如何显式释放由C接口返回的非基本类型(如结构体)内存。通过提供实例代码和解决方法,确保资源的有效管理和避免内存泄露。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值