重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

C++项目中如何调用python函数

这篇文章主要介绍“C++项目中如何调用python函数”,在日常操作中,相信很多人在C++项目中如何调用python函数问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”C++项目中如何调用python函数”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

创新互联基于分布式IDC数据中心构建的平台为众多户提供成都温江机房 四川大带宽租用 成都机柜租用 成都服务器租用。

代码如下,分别演示直接执行python语句、无返回无参数函数调用、返回单参数函数调用。返回多参数函数调用:

 #include 
  #include 
  using namespace std;
  //执行python命令
  void ExecPythonCommand()
  {
  //直接执行 

  PyRun_SimpleString("from time import time,ctime\n"
  "print 'Today is',ctime(time())\n");
  }
  //调用无参数函数
  void InvokeNoParm()
  {
  PyObject* pMod = NULL;
  PyObject* pFunc = NULL;
  //导入模块
  pMod = PyImport_ImportModule("Life");
  if(pMod)
  {
  //获取函数地址
  pFunc = PyObject_GetAttrString(pMod, "a");
  if(pFunc)
  {
  //函数调用
  PyEval_CallObject(pFunc, NULL);
  }
  else
  {
  cout << "cannot find function a" << endl;
  }
  }
  else
  {
  cout << "cannot find Life.py" << endl;
  }
  }

//调用一参数函数

 void InvokeWith2Parm()
  {
  PyObject* pMod = NULL;
  PyObject* pFunc = NULL;
  PyObject* pParm = NULL;
  PyObject* pRetVal = NULL;
  int   iRetVal = 0;
  //导入模块
  pMod = PyImport_ImportModule("FuncDef");
  if(pMod)
  {
  pFunc = PyObject_GetAttrString(pMod, "square");
  if(pFunc)
  {
  //创建参数
  pParm = Py_BuildValue("(i)", 5);
  //函数调用
  pRetVal = PyEval_CallObject(pFunc, pParm);
  //解析返回值
  PyArg_Parse(pRetVal, "i", &iRetVal);
  cout << "square 5 is: " << iRetVal << endl;
  }
  else
  {
  cout << "cannot find function square" << endl;
  }
  }
  else
  {
  cout << "cannot find FuncDef.py" << endl;
  }
  }

//调用多参数函数

 void InvokeWith3Parm()
  {
  PyObject* pMod = NULL;
  PyObject* pFunc = NULL;
  PyObject* pParm = NULL;
  PyObject* pRetVal = NULL;
  int   iRetVal = 0;
  //导入模块
  pMod = PyImport_ImportModule("add");
  if(pMod)
  {
  pFunc = PyObject_GetAttrString(pMod, "add");
  if(pFunc)
  {
  //创建两个参数
  pParm = PyTuple_New(2);
  //为参数赋值
  PyTuple_SetItem(pParm, 0, Py_BuildValue("i",2000));
  PyTuple_SetItem(pParm, 1, Py_BuildValue("i",3000));
  //函数调用
  pRetVal = PyEval_CallObject(pFunc, pParm);
  //解析返回值
  PyArg_Parse(pRetVal, "i", &iRetVal);
  cout << "2000 + 3000 = " << iRetVal << endl;
  }
  else
  {
  cout << "cannot find function square" << endl;
  }
  }
  else
  {
  cout << "cannot find add.py" << endl;
  }
  }
 int main(int argc, char* argv[])
  {
  Py_Initialize(); //python 解释器的初始化
  ExecPythonCommand();
  InvokeNoParm();
  InvokeWith2Parm();
  InvokeWith3Parm();
  Py_Finalize();  // 垃圾回收、清除导入库
  return 0;
  }

到此,关于“C++项目中如何调用python函数”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注创新互联网站,小编会继续努力为大家带来更多实用的文章!


网站标题:C++项目中如何调用python函数
文章网址:http://cqcxhl.com/article/gjhiog.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP