[C++-sig] Deriving Python function from C++ base class with pure virtual function

Jonathan Brandmeyer jbrandmeyer at earthlink.net
Sun Nov 14 23:35:14 CET 2004


On Sat, 2004-11-13 at 01:53 -0800, Paul F. Kunz wrote:
>    I'm deriving a Python class from a C++ class with both concrete and
> pure virtual functions.   I written a FunctionWrap C++ class that
> implements the pure virtual function, operator() (double) by invoking
> the call_method.   Then my Python class looks like...
> 
> from hippo import AbsFunction
> class Linear ( AbsFunction ) :
>     def __init__ ( self ) :
>         AbsFunction.__init__(self)
>         self.initialize ()
>     
>     def initialize ( self ) :
>         self.setName ( 'linear' )
>         self.setParmNames ( [ 'Intercept', 'Slope' ] )
>         self.setParameters ( [ intercept, slope ] )
>     
>     def valueAt ( self, x ) :
>         parms = self.getParameters ()
>         
>         return x * parms[1] + parms[0]
> 
> where AbsFunction is the Python name for the C++ base class and all
> the set and get functions are implemented in the C++ base class.  The
> FunctionWrap::operator ()(double) is implemented to call the Python
> valueAt method.  All this works within a Python script.
> 
>    However, I want to also call operator()(double) from C++ code in a
> different thread from the Python main thread.   This other thread is
> started with Qt's QThread class.   When I do this I get to
> FunctionWrap::operator()(double) and then seg fault with the following
> back trace in gdb...

See the PEP 311 interface PyGILState_Ensure()/PyGILState_Release(),
which you will use to wrap around the callback function in your C++
code.  This interface solves the thread bootstrap problem.  Furthermore,
the lock is recursive, so locking the GIL is safe when you already have
the lock.

HTH,
-Jonathan Brandmeyer




More information about the Cplusplus-sig mailing list