下面的函數需要一個python文件句柄,從文件讀取壓縮二進制數據,創建一個Python字典並返回它。如果我無休止地循環,它會不斷消耗RAM。我的RefCounting有什麼問題?爲什麼我的Python C擴展泄漏內存?
static PyObject* __binParse_getDBHeader(PyObject *self, PyObject *args){
PyObject *o; //generic object
PyObject* pyDB = NULL; //this has to be a py file object
if (!PyArg_ParseTuple(args, "O", &pyDB)){
return NULL;
} else {
Py_INCREF(pyDB);
if (!PyFile_Check(pyDB)){
Py_DECREF(pyDB);
PyErr_SetString(PyExc_IOError, "argument 1 must be open file handle");
return NULL;
}
}
FILE *fhDB = PyFile_AsFile(pyDB);
long offset = 0;
DB_HEADER *pdbHeader = malloc(sizeof(DB_HEADER));
fseek(fhDB,offset,SEEK_SET); //at the beginning
fread(pdbHeader, 1, sizeof(DB_HEADER), fhDB);
if (ferror(fhDB)){
fclose(fhDB);
Py_DECREF(pyDB);
PyErr_SetString(PyExc_IOError, "failed reading database header");
return NULL;
}
Py_DECREF(pyDB);
PyObject *pyDBHeader = PyDict_New();
Py_INCREF(pyDBHeader);
o=PyInt_FromLong(pdbHeader->version_number);
PyDict_SetItemString(pyDBHeader, "version", o);
Py_DECREF(o);
PyObject *pyTimeList = PyList_New(0);
Py_INCREF(pyTimeList);
int i;
for (i=0; i<NUM_DRAWERS; i++){
//epochs
o=PyInt_FromLong(pdbHeader->last_good_test[i]);
PyList_Append(pyTimeList, o);
Py_DECREF(o);
}
PyDict_SetItemString(pyDBHeader, "lastTest", pyTimeList);
Py_DECREF(pyTimeList);
o=PyInt_FromLong(pdbHeader->temp);
PyDict_SetItemString(pyDBHeader, "temp", o);
Py_DECREF(o);
free(pdbHeader);
return (pyDBHeader);
}
感謝您抽空看看,
LarsenMTL
Torsten,謝謝,我剛剛在你的4段中學到了更多,然後我整天早上都在盯着文檔。我會檢查所有我借用的和返回新的參考。 – Mark 2008-12-08 20:40:28