C++中嵌入Python

c++调用python的流程如下:

1:includt<boost/python.cpp>      ;注意不用导入<python.h>文件
2:初始化python解释器: Py_Initialize()
3 :  调用别的Python/C API做一些环境的初始化操作。比如把python的全局锁,到脚本加入到解释器的include路径下。
  1. PyRun_SimpleString("import sys");
    PyRun_SimpleString((std::string("if not '")+ m_scriptPath
    +"' in sys.path: sys.path.append('"+ m_scriptPath +"')").c_str());
Boost.python提供了3中运行python代码的方法;
object eval(str expression, object globals = object(), object locals = object())
object exec(str code, object globals = object(), object locals = object())
object exec_file(str filename, object globals = object(), object locals = object())
eval 执行表达式,exec执行语句,exec_file执行文件。 globals和locals变量是dict对象包含了代码运行的全局和本地环境
  1. object main_module =import("__main__");
    object main_namespace = main_module.attr("__dict__");
    object ignored = exec("result = 5 ** 2", main_namespace);
    int five_squared = extract<int>(main_namespace["result"]);
4:导入module:
python::import(std::string name)  相当python的import语句
 
6: tuple的用法
object[0]
 
7:dict的用法
dict["name"]
 
8:str的用法
  1. object main_module =import("__main__");
    object main_namespace = main_module.attr("__dict__");
    object ignored = exec("result = (3,4,6)", main_namespace);
    string str=python::extract<string>(python::str(main_namespace["result"][0]).encode("utf-8"));
    cout<<"result"<<str<<endl;
 
异常处理
  1. catch(...)
    {
    PyErr_Print();
    PyErr_Clear();
    PD_RC_CHECK( DBAAS_SYS_ERR, PDERROR,
    "Failed to delete vm, python error detected!");
    }
其实object还有很多方法,同时python的buildin函数在boost.python也有对象的方法 比如len
 
下面是一个对象调用的例子:
  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());
    python::object module = python::import("ModuleName");
    python::object global( module.attr("__dict__"));
    m_instService = global["ClassName"];
    python::object instService=m_instService();//调用构造函数,如果构造函数有参数,请传入。
    python::object createInstance=instService.attr("createInstance");//获取对象的方法
    ret = createInstance(int类型,std::string类型);//调用方法,返回一个object对象,如果要获取返回值需要对ret解析。使用extract
    std::string strRet=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!");
    }



原文地址:https://www.cnblogs.com/gaoxing/p/4335422.html