我正在使用ctypes将一些C函数从DLL公开到Python脚本。其中一个函数返回一个动态大小的字符数组,我希望能够在Python中读取这个数组的内容,但也可以使用property handle释放数组的内存。在
示例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代码:
^{pr2}$
这些代码都能像您预期的那样正常工作。我的问题是:因为ctypes.string_在在指定的内存位置创建一个字符串,当某些字符串超出Python解释器的作用域时,该内存将被垃圾回收,还是需要手动释放它?在