C++中怎么调用Python脚本

C++中怎么调用Python脚本,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

#test function   def add(a,b):       print "in python function add"       print "a = " + str(a)       print "b = " + str(b)       print "ret = " + str(a+b)       return     def foo(a):       print "in python function foo"       print "a = " + str(a)       print "ret = " + str(a * a)       return

把上面的PPython脚本代码存为pytest.py接下来是c++ 的代码:

#include "Python.h"   int main(int argc, char** argv)  {      // 初始化Python      //在使用Python系统前,必须使用Py_Initialize对其      //进行初始化。它会载入Python的内建模块并添加系统路      //径到模块搜索路径中。这个函数没有返回值,检查系统      //是否初始化成功需要使用Py_IsInitialized。       Py_Initialize();       // 检查初始化是否成功      if ( !Py_IsInitialized() )       {          return -1;      }       // 添加当前路径      //把输入的字符串作为Python代码直接运行,返回0      //表示成功,-1表示有错。大多时候错误都是因为字符串      //中有语法错误。      PyRun_SimpleString("import sys");      PyRun_SimpleString("sys.path.append('./')");      PyObject *pName,*pModule,*pDict,*pFunc,*pArgs;       // 载入名为pytest的脚本      pName = PyString_FromString("pytest");      pModule = PyImport_Import(pName);      if ( !pModule )      {          printf("can't find pytest.py");          getchar();          return -1;      }      pDict = PyModule_GetDict(pModule);      if ( !pDict )       {          return -1;      }       // 找出函数名为add的函数      pFunc = PyDict_GetItemString(pDict, "add");      if ( !pFunc || !PyCallable_Check(pFunc) )      {          printf("can't find function [add]");          getchar();          return -1;      }

看完上述内容,你们掌握C++中怎么调用Python脚本的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注行业资讯频道,感谢各位的阅读!