本文小编为大家详细介绍“C++项目如何调用python函数”,内容详细,步骤清晰,细节处理妥当,希望这篇“C++项目如何调用python函数”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

网站建设哪家好,找成都创新互联!专注于网页设计、网站建设、微信开发、小程序开发、集团企业网站建设等服务项目。为回馈新老客户创新互联还提供了五华免费建站欢迎大家使用!
代码如下,分别演示直接执行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函数”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注创新互联行业资讯频道。