我正在使用ctypes将一些C函数从DLL公开到Python脚本。其中一个函数返回一个动态大小的字符数组,我希望能够在Python中读取这个数组的内容,但是当我完成它时,属性句柄也会释放数组的内存。Python ctypes.string_at释放行为
的C语言代码:
...
#ifdef __cplusplus
extern "C"
{
#endif
__declspec(dllexport) char * WINAPI get_str()
{
int str_len = ... // figure out how long it is gonna be and set it here
char *ary = (char *)malloc(sizeof(char) * str_len);
// populate the array
...
ary[str_len - 1] = '\0';
return ary;
}
#ifdef __cplusplus
}
#endif
我建立我的DLL,它复制到它会被发现的位置,然后有这样的Python代码:
import ctypes
my_dll = ctypes.WinDLL("MyDLLName.dll")
some_str = ctypes.string_at(my_dll.get_str())
print some_str
此代码的所有工作正常正如你所期望的那样。我的问题是:因为ctypes.string_at在指定的内存位置创建一个字符串,当some_str超出Python解释器的范围时,该内存是否会被垃圾收集,或者我是否需要手动释放它?
2013-02-26
KSletmoe
+0
我可以有回答了我自己的问题......我写了一个无限循环,让它在重复调用my_dll.get_str()的同时运行,并观察我在Windows中的内存使用情况,并且似乎继续攀升。话虽如此,我仍然希望为了理智的缘故具体回答。 –
2013-02-26 03:19:31