我想從C/C++庫中獲取一些字符串,並將它們轉換爲python。我的代碼看起來是這樣的:在LIBPython ctypes:如何釋放內存?獲取無效指針錯誤
代碼:
const char* get(struct something *x)
{
[...]
// buf is a stringstream
return strdup(buf.str().c_str());
}
void freeme(char *ptr)
{
free(ptr);
}
Python代碼:
fillprototype(lib.get, c_char_p, POINTER(some_model)])
fillprototype(lib.freeme, None, [c_char_p])
// what i want to do here: get a string into python so that i can work
// with it and release the memory in the lib.
c_str = lib.get(some_model)
y = ''.join(c_str)
lib.freeme(c_str)
如果我打印()c_str,一切都在那裏。問題是(或似乎是)在最後一個Python行中。我無法釋放內存 - 庫正在弄錯指針。我在這裏做錯了什麼? (並請不要建議boost :: python左右)。
*** glibc detected *** python2: munmap_chunk(): invalid pointer: 0x00000000026443fc ***
爲什麼'get'返回'const char *',但'freeme'期望'char *'?你是否期望你的調用者拋棄const? –
好點..不幸的是,沒有解決問題。 –
這是32位還是64位的代碼?你知道錯誤發生在哪一行嗎?它不一定是「免費(ptr)」。 –