#include "Python.h" #include static PyObject *ErrorObject; /* ----------------------------------------------------- */ static char memdbg_stats__doc__[] = "Returns brief summary statistics using mallinfo()." ; static PyObject * memdbg_stats(PyObject *self, PyObject *args) { int used_percent; char buf[1024]; struct mallinfo info = mallinfo(); if (!PyArg_ParseTuple(args, ":stats")) return NULL; used_percent = (int)(info.uordblks * 100.0 / (info.uordblks + info.fordblks)); snprintf(buf, sizeof(buf), "allocated_bytes %10d\n" " used_bytes %10d\n" " unused_bytes %10d\n" "used_percent %10d\n" "unused_chunks %10d\n" "mmap_bytes %10d\n" "mmap_regions %10d\n", info.arena, info.uordblks, info.fordblks, used_percent, info.ordblks, info.hblkhd, info.hblks); buf[sizeof(buf) - 1] = 0; return PyString_FromString(buf); } static char memdbg_trim__doc__[] = "Release all but __pad bytes of freed top-most memory back to the\n" "system, using malloc_trim(). Return 1 if successful, else 0." ; static PyObject * memdbg_trim(PyObject *self, PyObject *args) { int res; int pad = 0; if (!PyArg_ParseTuple(args, "|i:trim", &pad)) return NULL; res = malloc_trim(pad); return PyInt_FromLong(res); } /* List of methods defined in the module */ static struct PyMethodDef memdbg_methods[] = { {"stats", (PyCFunction)memdbg_stats, METH_VARARGS, memdbg_stats__doc__}, {"trim", (PyCFunction)memdbg_trim, METH_VARARGS, memdbg_trim__doc__}, {NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */ }; /* Initialization function for the module (*must* be called initmemdbg) */ static char memdbg_module_documentation[] = "An interface to some functions provided by glibc's malloc implementation" ; void initmemdbg() { PyObject *m, *d; /* Create the module and add the functions */ m = Py_InitModule4("memdbg", memdbg_methods, memdbg_module_documentation, (PyObject*)NULL,PYTHON_API_VERSION); /* Add some symbolic constants to the module */ d = PyModule_GetDict(m); ErrorObject = PyString_FromString("memdbg.error"); PyDict_SetItemString(d, "error", ErrorObject); /* XXXX Add constants here */ /* Check for errors */ if (PyErr_Occurred()) Py_FatalError("can't initialize module memdbg"); }