Embed Python in C + +

Source: Internet
Author: User
Tags object object

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.
    1. 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
  1.  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
  1. 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
    1. 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:
  1. 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&LT;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 + +

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.