PyObject* PyImport_Import(PyObject* name)

Imports the module named in Python string object name and returns a new reference to the module object, like Python’s __import_ _( name ). PyImport_Import is the highest-level, simplest, and most often used way to import a module.

Beware, in particular, of using function PyImport_ImportModule, which may often look more convenient because it accepts a char* argument. PyImport_ImportModule operates on a lower level, bypassing any import hooks that may be in force, so extensions that use it will be far harder to incorporate in packages such as those built by tools py2exe and Installer, covered in Chapter 26. Therefore, always do your importing by calling PyImport_Import, unless you have very specific needs and know exactly what you’re doing.

To add functions to a module (or non-special methods to new types, as covered later in Section 24.1.12), you must describe the functions or methods in an array of PyMethodDef structures, and terminate the array with a sentinel (i.e., a structure whose fields are all 0 or NULL). PyMethodDef is defined as follows:

typedef struct {
    char* ml_name;        /* Python name of function or method */
    PyCFunction ml_meth;  /* pointer to C function impl */
    int ml_flags;         /* flag describing how to pass arguments */
    char* ml_doc;         /* docstring for the function or method */
} PyMethodDef

You must cast the second field to (PyCFunction) unless the C function’s signature is exactly PyObject* function (PyObject* ...

Get Python in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.