Next: Compilation and linkage Up: Extending Python with Previous: Back to the

The module's function table

I promised to show how I made the function posix_system() callable from Python programs. This is shown later in `Modules/posixmodule.c':


    static struct methodlist posix_methods[] = {
        ...
        {"system",  posix_system},
        ...
        {NULL,      NULL}        /* Sentinel */
    };

    void
    initposix()
    {
        (void) initmodule("posix", posix_methods);
    }

(The actual initposix() is somewhat more complicated, but many extension modules can be as simple as shown here.) When the Python program first imports module posix, initposix() is called, which calls initmodule() with specific parameters. This creates a `module object' (which is inserted in the table sys.modules under the key 'posix'), and adds built-in-function objects to the newly created module based upon the table (of type struct methodlist) that was passed as its second parameter. The function 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 you don't need to check for errors.


guido@cwi.nl