Problem calling Python methods from C

Stephen Kellett snail at objmedia.demon.co.uk
Fri Jun 3 06:51:18 EDT 2005


Hello everyone,

I'm trying to do something in C calling Python and its failing. I'd be
grateful if you could take a look and hopefully you have an answer.

What I'm trying to do is determine the address of the "collect" function
in the "gc" module. I want to do this so that we can determine when a
garbage collection happens, regardless of how it is triggered
(explicitly by a user call, or implicitly by the behaviour of the
program allocating lots of data).

As far as I can tell, the gc.collect function is not exposed as a C API,
so I cannot hook that to do the monitoring I want. Therefore the only
way to get the address to hook is to inspect the Python module function
dictionaries, well I think its the only way :-)

The approach is to get the module that holds "gc". You can do this by
calling PyImport_AddModule for an existing module - it will return it.
Then you get the dictionary of methods from the module and lookup the
method in there. Well, that was my theory after looking at the Python
source code.
I've shown the source code below.

// get "collect" method from GC module
// this module should always be present
// as it is a fundamental part of Python

PyObject        *module;
DWORD   funcAddress = NULL;

module = PyImport_AddModule("gc");
if (module != NULL)
{
        // get dictionary of methods for this module

        PyObject        *dict;

        dict = PyModule_GetDict(module);
        if (dict != NULL)
        {
                // lookup "collect" in the dictionary

                PyObject        *func;
                int             numItems;

                // check we have some elements,
                // strangely there are only 2

                numItems = PyDict_Size(dict);

                // this works, good, that is expected

                func = PyDict_GetItemString(dict, "__name__");

                // this fails, why? "collect" is a method in "gc"
                // I would expect it to work

                func = PyDict_GetItemString(dict, "collect");
        }
}

Hopefully someone can shed some light on why this doesn't work, or
explain what the correct method should be if I am doing the wrong thing.

Answers as descriptions, Python or C most welcome.

Cheers

Stephen
-- 
Stephen Kellett
Object Media Limited    http://www.objmedia.demon.co.uk/software.html
Computer Consultancy, Software Development
Windows C++, Java, Assembler, Performance Analysis, Troubleshooting



More information about the Python-list mailing list