Extending and Embedding Python, Release 3.9.5 Chapter 2. Creating extensions without third party tools 54 Concretely, here is how a trivial object structure would be augmented with the required field: typedef struct { PyObject_HEAD PyObject *weakreflist; /* List of weak references */ } TrivialObject; static PyTypeObject TrivialType ={ PyVarObject_HEAD_INIT(NULL ,0) /* ... other members omitted for brevity ... */ .tp_weaklistoffset =offsetof(TrivialObject, weakreflist), }; static void Trivial_dealloc(TrivialObject *self) { /* Clear weakrefs first before calling any destructors */ if (self ->weakreflist!=NULL ) PyObject_ClearWeakRefs((PyObject *) self); /* ... remainder of destruction code omitted for brevity ... */ Py_TYPE(self) ->tp_free((PyObject *) self); } if (!PyObject_TypeCheck(some_object, &MyType)) { PyErr_SetString(PyExc_TypeError, "arg #1 not a mything "); return NULL ; } 2.4 Building C and C++ Extensions And the corresponding member in the statically-declared type object: The only further addition is that tp_dealloc needs to clear any weak references (by calling PyObject_ClearWeakRefs() ) if the field is non-$_{NULL}$ : In order to learn how to implement any specific method for your new data type, get the CPython source code. Go to the $_{Objects}$directory, then search the C source files for $_{tp_}$plus the function you want (for example, tp_richcompare ). You will find examples of the function you want to implement. When you need to verify that an object is a concrete instance of the type you are implementing, use the PyObject_TypeCheck() function. A sample of its use might be something like the following: See also: A C extension for CPython is a shared library (e.g. a $_{.so}$file on Linux, .pyd on Windows), which exports an initialization function . To be importable, the shared library must be available on$_{PYTHONPATH}$ , and must be named after the module name, with an appropriate extension. When using distutils, the correct filename is generated automatically. The initialization function has the signature: PyObject*$_{PyInit_modulename}$ ( void$_{)}$ Download CPython source releases. https://www.python.org/downloads/source/ The CPython project on GitHub, where the CPython source code is developed. https://github.com/python/ cpython 2.3.7 More Suggestions