温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++项目中怎么调用python函数

发布时间:2021-07-05 18:17:32 来源:亿速云 阅读:216 作者:Leah 栏目:编程语言

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

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

 #include <Python.h>
  #include <iostream>
  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函数的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI