Getting module object by name in C extension module

Nick Smallbone nick at nick8325.freeserve.co.uk
Wed Jul 14 06:44:21 EDT 2004


"Ilariu Raducan" <ilariu at yahoo.com> wrote in message
news:ps7Jc.4541$Z14.5668 at news.indigo.ie...
> Hi All,
>
> Is it possible in a C extension module to get a reference to an already
loaded module?
> Something like:
> PyObject* module_object = Py......("module_name");
>
> Thank You,
> Ilariu

I haven't written any C extensions for a while, but looking at the
documentation this seems to be the way to go:

PyObject * modules = PyImport_GetModuleDict();
PyObject * module_object = PyDict_GetItemString(modules, "module_name");

The first line gets the value of sys.modules, and the second line looks up
the module name in it. Both of those are borrowed references, so you don't
need to Py_DECREF() them.

If the module might not have been loaded, you can do this:

PyObject * module_object = PyImport_Import("module_name");

but then you have to Py_DECREF() module_object once you're finished.

Nick





More information about the Python-list mailing list