[C++-sig] calling a python-callback-function from a c++thread...

Lars Kunert lkunert at mpi-sb.mpg.de
Fri Sep 26 19:23:14 CEST 2003


Hi!

I am trying to implement a Qt-application, which after beeing lauched from 
the IDLE creates and lives on its own thread. The idea is, that the 
program may be called from other python-programs and may itself call other 
python programs.
Python-functions, which should be called from the program, register 
themself prior to their invocation. I think my problem is that I do not 
aquire the python-interpreter lock before using the callback...

PyApp.* wraps QtApplication by exporting selected methods to pyton, 
launches the thread, QtApp lives on, and locks/unlockes (syncs) accesses 
to the internal state of QtApp.
PyApp.h

class PyApp
{
  private:
    Thread *thread;
    QtApp *app;
 ...

    void set_callback( PyObject *callback );
};



PyApp.cxx

BOOST_PYTHON_MODULE(PyApp_module)
{
    class_< PyApp >("App", init<  >())
        .def(init< const PyApp & >())
        .def("set_callback", &PyApp::set_callback)
    ;
}


void PyApp::set_callback( PyObject *callback )
{
    app->lock(); {

        app->set_callback( callback );

    }; app->unlock();
};


QtApp.* is a "normal"QtApplication, which tries to use a callback and 
dies... 
QtApp.h:

class QtApp : public QtApplication {
...
private:
    PyObject *_callback;

public
     void set_callback( PyObject *callback ); 
     void callback();
...
}


QtApp.cxx:

...
void  QtApp::callback() 
{
    boost::python::call<void>( _callback );
};


EXAMPLE
>>> from PyApp_module import App
>>> a=App()
>>> dir(a)
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', 
'__hash__', '__init__', '__instance_size__', '__module__', '__new__', 
'__reduce__', '__repr__', '__setattr__', '__str__', '__weakref__', 'exec', 
'set_callback', 'set_text', 'text']
>>> def ph():
...     print( "hallo" )
...
>>> ph()
hallo
>>> a.set_callback( ph )
<----now I invoke the callback (by pressing a button on the application 
window)
>>> Segmentation fault



I hope the preceeding code-snips will help to explain the situation 
sufficiently. If there are requests, I can also post the complete 
test-application...


Thanks for your help,

Lars




More information about the Cplusplus-sig mailing list