diff Objects/typeobject.c @ 35999:9541369b0dca legacy-trunk

Add const to several API functions that take char *. In C++, it's an error to pass a string literal to a char* function without a const_cast(). Rather than require every C++ extension module to put a cast around string literals, fix the API to state the const-ness. I focused on parts of the API where people usually pass literals: PyArg_ParseTuple() and friends, Py_BuildValue(), PyMethodDef, the type slots, etc. Predictably, there were a large set of functions that needed to be fixed as a result of these changes. The most pervasive change was to make the keyword args list passed to PyArg_ParseTupleAndKewords() to be a const char *kwlist[]. One cast was required as a result of the changes: A type object mallocs the memory for its tp_doc slot and later frees it. PyTypeObject says that tp_doc is const char *; but if the type was created by type_new(), we know it is safe to cast to char *.
author Jeremy Hylton <jeremy@alum.mit.edu>
date Sat, 10 Dec 2005 18:50:16 +0000
parents 1c4d192f1568
children 2eb78f5d1450
line wrap: on
line diff
--- a/Objects/typeobject.c	Sat Dec 10 17:44:27 2005 +0000
+++ b/Objects/typeobject.c	Sat Dec 10 18:50:16 2005 +0000
@@ -21,7 +21,7 @@
 static PyObject *
 type_name(PyTypeObject *type, void *context)
 {
-	char *s;
+	const char *s;
 
 	if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
 		PyHeapTypeObject* et = (PyHeapTypeObject*)type;
@@ -1556,7 +1556,7 @@
 type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
 {
 	PyObject *name, *bases, *dict;
-	static char *kwlist[] = {"name", "bases", "dict", 0};
+	static const char *kwlist[] = {"name", "bases", "dict", 0};
 	PyObject *slots, *tmp, *newslots;
 	PyTypeObject *type, *base, *tmptype, *winner;
 	PyHeapTypeObject *et;
@@ -1856,12 +1856,13 @@
 		PyObject *doc = PyDict_GetItemString(dict, "__doc__");
 		if (doc != NULL && PyString_Check(doc)) {
 			const size_t n = (size_t)PyString_GET_SIZE(doc);
-			type->tp_doc = (char *)PyObject_MALLOC(n+1);
-			if (type->tp_doc == NULL) {
+                        char *tp_doc = PyObject_MALLOC(n+1);
+			if (tp_doc == NULL) {
 				Py_DECREF(type);
 				return NULL;
 			}
-			memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
+			memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
+                        type->tp_doc = tp_doc;
 		}
 	}
 
@@ -2105,7 +2106,10 @@
 	Py_XDECREF(type->tp_mro);
 	Py_XDECREF(type->tp_cache);
 	Py_XDECREF(type->tp_subclasses);
-	PyObject_Free(type->tp_doc);
+        /* A type's tp_doc is heap allocated, unlike the tp_doc slots
+         * of most other objects.  It's okay to cast it to char *.
+         */
+	PyObject_Free((char *)type->tp_doc);
 	Py_XDECREF(et->name);
 	Py_XDECREF(et->slots);
 	type->ob_type->tp_free((PyObject *)type);