3rdParty/boost/1.78.0/libs/python/doc/html/reference/embedding.html
| |
Exposes a mechanism for embedding the python interpreter into C++ code.
evalobjecteval(strexpression,objectglobals=object(),objectlocals=object());
Effects
Evaluate Python expression from expression in the context specified by the dictionaries globals and locals.
Returns
An instance of object which holds the value of the expression.
execobjectexec(strcode,objectglobals=object(),objectlocals=object());
Effects
Execute Python source code from code in the context specified by the dictionaries globals and locals.
Returns
An instance of object which holds the result of executing the code.
exec_fileobjectexec\_file(strfilename,objectglobals=object(),objectlocals=object());
Effects
Execute Python source code from the file named by filename in the context specified by the dictionaries globals and locals.
Returns
An instance of object which holds the result of executing the code.
The following example demonstrates the use of import and exec to define a function in python, and later call it from within C++.
#include\<iostream\>#include\<string\>usingnamespaceboost::python;voidgreet(){// Retrieve the main module.objectmain=import("\_\_main\_\_");// Retrieve the main module's namespaceobjectglobal(main.attr("\_\_dict\_\_"));// Define greet function in Python.objectresult=exec("def greet(): \n"" return 'Hello from Python!' \n",global,global);// Create a reference to it.objectgreet=global["greet"];// Call it.std::stringmessage=extract\<std::string\>(greet());std::cout\<\<message\<\<std::endl;}
Instead of embedding the python script into a string, we could also store it in an a file...
defgreet():return'Hello from Python!'
... and execute that instead.
// ...// Load the greet function from a file.objectresult=exec\_file(script,global,global);// ...}
| | Copyright © 2002-2005, 2015 David Abrahams, Stefan Seefeld
Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt
|