Getting module object by name in C extension module

I

Ilariu Raducan

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
 
N

Nick Smallbone

Ilariu Raducan said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top