Search code examples
pythonpython-c-api

Passing python method's reference to C as callback


Can we pass a reference of python method as an argument to C. This method is a callback method which will be executed after the C code has been executed.


Solution

  • In the Python C-API, Python objects are simply PyObject references. PyObject references can be called using PyObject_Call (if you want to have more descriptive errors, you can call PyCallable_Check, first.)

    Assuming you've extended a module using the API you would have a method as follows:

    bool call_method(PyObject *method)
    {
        PyObject *args = PyTuple_New(0);
        if ( NULL == PyObject_Call(method, args, NULL) )
        {
            // Method call failed
            return false;
        }
        return true;
    }
    

    Then, in Python, you call the method using the following:

    import my_module as bla
    
    bla.call_method(myClass.myMethod)