[C++-sig] [Boost.Python] imports and callbacks

Tanguy Fautre tanguy.fautre at spaceapplications.com
Thu Nov 16 17:49:20 CET 2006


Hi,

Here is an example Python class that will be executed by an embedded 
Python interpreter:

import math;


class Subsystem:

     def __init__(self) :
         simulation.event.register(self.event_callback)


     def event_callback(self) :
         #import math
         cosine = math.cos(simulation_time)


new_subsystem = Subsystem()



As you can see, at construction the Subsystem class registers a callback 
functions via the simulation.event object.

The simulation.event object is a C++ object exported via Boost.Python 
into the main namespace. The simulation.event.register function in C++ 
has only one argument: a boost::python::object to copy the given callback.

Lets say this boost::python::object is named Function. When I call 
Function(), the callback is correctly called.
The interpreter however complains that math.cos is unknown (i.e. 
ignoring the "import math;" at the beginning of the python code).

If I uncomment #import math in the event_callback definition, everything 
works fine.

At first I thought that boost::python::object was ignoring both the 
local and the main namespaces used by the embedded python interpreter 
when event_callback was registered. But I realized later that I could 
still access objects in the main namespace such as the simulation.event 
object.

Is it possible that the top "import math" only affects the local 
namespace, and that this local namespace is not reused when the 
callbacked is called through a boost::python::object ?

Also, what is the performance impact of the "import math" in the 
callback? Putting the import inside event_callback is not very annoying, 
as long as it does not affect performances.


Tanguy




More information about the Cplusplus-sig mailing list