[C++-sig] Re: Presenting a Python embedding tutorial

Dirk Gerrits dirk at gerrits.homeip.net
Wed Dec 11 16:53:51 CET 2002


Charsley, Mark wrote:
>>>That contains a dangerous flaw - it supposes that 
>>
>>PyInitialize hasn't been
>>
>>>called by anyone else, using code other than boost::python. 
>>
>>Which means that
>>
>>>code running in a boost::python extension can't create a 
>>
>>sub-interpreter
>>
>>>using boost::python. I strongly advise using 
>>
>>Py_IsInitialized() instead of a
>>
>>>static count in a C++ class.
>>
>>Right. Good point. But how do you propose to fix the destructor?
> 
> 
> A variation on this (a minimal Embedding class we developed here before
> boost::python v2)?
> 
> ScriptEngine::ScriptEngine()
> {
>     if(Py_IsInitialized())
>     {
>         m_weControlPython = false;
>     }
>     else
>     {
>         Py_Initialize();
>         m_weControlPython = true;
>     }
> }
> 
> ScriptEngine::~ScriptEngine()
> {
>     if (m_weControlPython)
>     {
>         Py_Finalize();
>     }
> }

Yes very nice. But I still think the static counter is needed for the 
sub-interpreters. How about this:

     interpreter()
     {
         // Create the main interpreter
         if (interpreter_count == 0)
         {
             if (Py_IsInitialized())
             {
                 we_control_python = false;
             }
             else
             {
                 Py_Initialize();
                 we_control_python = true;
             }
             ...
         }
         // Create a sub-interpreter
         else
         {
             ...
         }
         interpreter_count++;
     }
     ~interpreter()
     {
         // Release the main interpreter
         if (interpreter_count == 1)
         {
             if (we_control_python)
                 Py_Finalize();
             ...
         }
         // Release a sub-interpreter
         else
         {
             ...
         }
         interpreter_count--;
     }

??

Dirk Gerrits







More information about the Cplusplus-sig mailing list