The process for calling Python in C + + is as follows:
1:includt<boost/python.cpp>; note Do not import <python.h> file 2: Initialize Python interpreter: Py_initialize () 3: Invoke other PYTHON/C APIs to do some environment Initialization of the operation. For example, a Python global lock to a script added to the interpreter's include path.
Pyrun_simplestring ("import sys"); Pyrun_simplestring (std::string("ifnot") + M_scriptpath+ "' in Sys.path:sys.path.append ('"+ M_scriptpath +"')" ). C_STR ());
Boost.python provides a way to run Python code in 3;
Object Object Object Object Object ())objectObject Object Object Object()) ObjectObject Object Object Object ())
Eval executes the expression, EXEC executes the statement, and Exec_file executes the file. The globals and locals variables are dict objects that contain the global and local environment in which the code runs
object main_module =import ( " __main__ ); object main_namespace = main_module.attr ( " __dict__ " object ignored = EXEC ( result = 5 * * 2 " int five_squared = Extract<int > ( Main_namespace[ "]);
4: Import module:python::import (std::string name) rather python import statement 6:tuple usage object[0] 7:dict usage dict["name"] 8:str
ObjectMain_module =import ("__main__");ObjectMain_namespace = Main_module.attr ("__dict__");Objectignored = EXEC ("result = (3,4,6)", main_namespace);stringstr=python::extract<string> (Python::str (main_namespace["result"][0]). Encode ("Utf-8")); cout<<"result"<<str<<endl;
Exception handling
Catch (...) {Pyerr_print (); Pyerr_clear (); Pd_rc_check (Dbaas_sys_err, Pderror,"Failed to delete vm, python error detected! " );}
In fact, there are many methods of object, while the Python Buildin function in Boost.python also has object methods such as Len Below is an example of an object invocation:
Try{Pythonexecthrlock _pylock; Pyrun_simplestring ("Import SYS"); Pyrun_simplestring (std::string("if not '")+M_scriptpath+"' in Sys.path:sys.path.append ('"+ M_scriptpath +"')"). C_STR ());p Ython::Objectmodule = Python::import ("ModuleName");p Ython::Object Global(Module.attr ("__dict__")); M_instservice=Global["ClassName"];p Ython::ObjectInstservice=m_instservice ();//call the constructor, if the constructor has parameters, pass in. Python::ObjectCreateinstance=instservice.attr ("CreateInstance");//methods to get Objectsret = CreateInstance (int type, std::string type);//invokes a method that returns an object if the return value needs to be parsed on a ret. Using extractSTD::stringSTRRET=PYTHON::EXTRACT<STD::string> (str (Result). Encode ("Utf-8"))}Catch(...) {Pythonexecthrlock _pylock; Pyerr_print (); Pyerr_clear (); Pd_rc_check (Dbaas_sys_err, Pderror,"Failed to init alicloudvmprovider, python error detected!");}
Embed Python in C + +