It is possible to pass a Python callback to C-extensions?

Robin Becker robin at
Wed Aug 20 18:17:22 CEST 2003

In article <OKM0b.2109$c_.88851 at>, Pierre Rouleau
<prouleau_nospam_atall_ at> writes
>I have a GUI application written in Python (with WxPython) which uses 
>some low level classes also written in Python.  These low level Python 
>classes are given a pointer to some GUI Python object.  The low level 
>Python classes callback some of the methods of the GUI object.  All 
>works fine.
>Now I want to convert the low level Python classes to C++.  I will be 
>using SWIG to create the marshaling so the top level GUI, written in 
>Python stays that way.
>The problem:  is it possible to continue using call backs?  The C++ code 
>would need to call the Python methods back.  Is there an easy way to do 
certainly you can call back into python, I have some typical code that
looks like

        PyObject        *callback;
        PyObject        *arglist;
        PyObject        *result;

        arglist = Py_BuildValue("(s)",buf);
        result = PyEval_CallObject(callback, arglist);
        else {
                /*handle error*/

Of course you need to get the definition of  callback somehow. But that
is easy via argument passing or obtaining a global function.

>This is a little different from extending or embedding.  I have a Python 
>program that uses Python extensions written in C++.  This C++ code would 
>need to pass some information back to the Python code (and currently, 
>the all-round Python code uses call backs).
>Thanks in advance for any help.

Robin Becker

More information about the Python-list mailing list