[C++-sig] Executing python code from C++

Stefan Seefeld seefeld at sympatico.ca
Sun Feb 7 15:51:42 CET 2010


On 02/07/2010 08:29 AM, Murray Cumming wrote:
> So, I guess I can use boost::python::exec() to call code that defines a
> Python function.
>    

bpl::exec() executes a chunk of Python code, no matter what it contains.

> But how can I get a boost::python::object for the (callable object of)
> the function? In C, I'm using PyDict_GetItemString() for that.
>    

Sorry, I don't understand the question. Can you give an example of what 
you want to do ? May be you want to "exec" some python code that defines 
a function, which you then want to extract and call later ?
That may look like this:

   // Retrieve the main module
   bpl::object main = bpl::import("__main__");
   // Retrieve the main module's namespace
   bpl::object global(main.attr("__dict__"));
   // Define the 'embedded' Python code...
   std::string py_code = "def greeting(): print 'hello world !'";
   // ...and execute it.
   bpl::object result = bpl::exec(py_code, global, global);
   // Extract the function
   bpl::object greeting = global["greeting"];
   // Call it
   greeting();

You may combine this with the other techniques outlines previously. For 
example, your Python code may define types based on previously exported 
C++ types (Python classes derived from C++ classes, say), and then 
extract them to gain back C++ references to base classes. There are 
endless possibilities to play with such hybrid code... :-)

     Stefan

-- 

       ...ich hab' noch einen Koffer in Berlin...



More information about the Cplusplus-sig mailing list