C DLL to Python Callback
Question: I have a Visual C++ DLL. I have a SetCallback( function-pointer) exported in
the DLL. I use this function to set a callback function from a python2.7
script. I follow what is given in the Python documentation.

    
    
    from ctypes import *
    def mypy_callback(number):
        print str(number)
    
    d = cdll.LoadLibrary(r"myfunctions.dll")
    callback_type = CFUNCTYPE(None, c_int )
    d.SetCallback(callback_type(mypy_callback))
    

In the C code I have

    
    
    typedef void (*callback_function)(int);
    void SetCallback(callback_function aCallback)
    {
        py_callback = aCallback;
    }
    

When I call this function from C DLL, like so: py_callback(999), python just
crashes. What could I be doing wrong?


Answer: The following callback indirection will solve this problem:

    
    
    d = cdll.LoadLibrary(r"myfunctions.dll")
    callback_type = CFUNCTYPE(None, c_int )
    callback = callback_type(mypy_callback)
    d.SetCallback(callback)
    

