From b14d8c9bcfb7f58e83a5c18c8b6eac0fa261c4b6 Mon Sep 17 00:00:00 2001 From: Meador Inge Date: Mon, 23 Jul 2012 10:01:29 -0500 Subject: Issue #15402: Add a __sizeof__ method to struct.Struct. Initial patch by Serhiy Storchaka. --- Modules/_struct.c | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) (limited to 'Modules/_struct.c') diff --git a/Modules/_struct.c b/Modules/_struct.c index 1604b90dfd..0a09fd8a82 100644 --- a/Modules/_struct.c +++ b/Modules/_struct.c @@ -1665,6 +1665,22 @@ s_get_size(PyStructObject *self, void *unused) return PyLong_FromSsize_t(self->s_size); } +PyDoc_STRVAR(s_sizeof__doc__, +"S.__sizeof__() -> size of S in memory, in bytes"); + +static PyObject * +s_sizeof(PyStructObject *self) +{ + Py_ssize_t size; + formatcode *code; + + size = sizeof(PyStructObject) + sizeof(formatcode); + for (code = self->s_codes; code->fmtdef != NULL; code++) { + size += sizeof(formatcode); + } + return PyLong_FromSsize_t(size); +} + /* List of functions */ static struct PyMethodDef s_methods[] = { @@ -1673,6 +1689,7 @@ static struct PyMethodDef s_methods[] = { {"unpack", s_unpack, METH_O, s_unpack__doc__}, {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS, s_unpack_from__doc__}, + {"__sizeof__", (PyCFunction)s_sizeof, METH_NOARGS, s_sizeof__doc__}, {NULL, NULL} /* sentinel */ }; -- cgit v1.2.1