Extending and Embedding Python, Release 3.9.5 Chapter 2. Creating extensions without third party tools 24 Note: We recommend using C99-style designated initializers as above, to avoid listing all the$_{PyTypeObject}$ fields that you don’t care about and also to avoid caring about the fields’ declaration order. Now that’s quite a bit to take in at once, but hopefully bits will seem familiar from the previous chapter. This file defines three things: The first bit is: This is what a Custom object will contain. $_{PyObject_HEAD}$is mandatory at the start of each object struct and defines a field called$_{ob_base}$of type$_{PyObject}$, containing a pointer to a type object and a reference count (these can be accessed using the macros$_{Py_REFCNT}$ and$_{Py_TYPE}$ respectively). The reason for the macro is to abstract away the layout and to enable additional fields in debug builds. Note: There is no semicolon above after the$_{PyObject_HEAD}$macro. Be wary of adding one by accident: some compilers will complain. Of course, objects generally store additional data besides the standard$_{PyObject_HEAD}$boilerplate; for example, here is the definition for standard Python floats: The second bit is the definition of the type object. static PyTypeObject CustomType={ PyVarObject_HEAD_INIT(NULL ,0) .tp_name ="custom.Custom ", .tp_doc="Custom objects", .tp_basicsize= sizeof (CustomObject), .tp_itemsize=0, .tp_flags =Py_TPFLAGS_DEFAULT, .tp_new=PyType_GenericNew, }; typedef struct { PyObject_HEAD double ob_fval; } PyFloatObject; typedef struct { PyObject_HEAD } CustomObject; Py_INCREF(&CustomType); if (PyModule_AddObject(m, "Custom", (PyObject*)&CustomType)<0) { Py_DECREF( &CustomType); Py_DECREF(m); return NULL ; } return m; } 1. What a Custom object contains: this is the CustomObject struct, which is allocated once for each Custom instance. 2. How the$_{Custom}$ type behaves: this is the$_{CustomType}$struct, which defines a set of flags and function pointers that the interpreter inspects when specific operations are requested. 3. How to initialize the custom module: this is the PyInit_custom function and the associated custommodule struct. (continued from previous page)