Name
PyImport_Import
Synopsis
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 */ PyCFunctionml_meth
; /* pointer to C function impl */ intml_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 books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.