标签:
c++调用python的流程如下:
PyRun_SimpleString("import sys"); PyRun_SimpleString((std::string("if not ‘")+ m_scriptPath +"‘ in sys.path: sys.path.append(‘"+ m_scriptPath +"‘)").c_str());
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())
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"]);
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;
catch(...) { PyErr_Print(); PyErr_Clear(); PD_RC_CHECK( DBAAS_SYS_ERR, PDERROR, "Failed to delete vm, python error detected!"); }
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!"); }
标签:
原文地址:http://www.cnblogs.com/gaoxing/p/4335422.html