私はctypesを使用して、DLLからPythonスクリプトにいくつかのC関数を公開しています。関数の1つは、動的なサイズの文字配列を返します。この配列の内容をPythonで読み取れるようにしたいだけでなく、プロパティハンドルを使用して、配列のメモリを解放します。
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インタープリターのスコープ外になると、そのメモリはガベージコレクションされますか、それとも手動で解放する必要がありますか?