next up previous contents index
Next: 1.6 Compilation and Linkage Up: Extending Python with C Previous: 1.4 Back to the

1.5 The Module's Method Table and Initialization Function

I promised to show how spam_system() is called from Python programs. First, we need to list its name and address in a ``method table'':

    static PyMethodDef SpamMethods[] = {
        ...
        {"system",  spam_system, 1},
        ...
        {NULL,      NULL}        /* Sentinel */
    };

Note the third entry (`1'). This is a flag telling the interpreter the calling convention to be used for the C function. It should normally always be `1'; a value of `0' means that an obsolete variant of PyArg_ParseTuple() is used.

The method table must be passed to the interpreter in the module's initialization function (which should be the only non-static item defined in the module file):

    void
    initspam()
    {
        (void) Py_InitModule("spam", SpamMethods);
    }

When the Python program imports module spam for the first time, initspam() is called. It calls Py_InitModule(), which creates a ``module object'' (which is inserted in the dictionary sys.modules under the key "spam"), and inserts built-in function objects into the newly created module based upon the table (an array of PyMethodDef structures) that was passed as its second argument. Py_InitModule() returns a pointer to the module object that it creates (which is unused here). It aborts with a fatal error if the module could not be initialized satisfactorily, so the caller doesn't need to check for errors.



guido@cnri.reston.va.us