您好,登錄后才能下訂單哦!
C++項(xiàng)目中怎么調(diào)用python函數(shù),相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。
代碼如下,分別演示直接執(zhí)行python語(yǔ)句、無(wú)返回?zé)o參數(shù)函數(shù)調(diào)用、返回單參數(shù)函數(shù)調(diào)用。返回多參數(shù)函數(shù)調(diào)用:
#include <Python.h> #include <iostream> using namespace std; //執(zhí)行python命令 void ExecPythonCommand() { //直接執(zhí)行 PyRun_SimpleString("from time import time,ctime\n" "print 'Today is',ctime(time())\n"); } //調(diào)用無(wú)參數(shù)函數(shù) void InvokeNoParm() { PyObject* pMod = NULL; PyObject* pFunc = NULL; //導(dǎo)入模塊 pMod = PyImport_ImportModule("Life"); if(pMod) { //獲取函數(shù)地址 pFunc = PyObject_GetAttrString(pMod, "a"); if(pFunc) { //函數(shù)調(diào)用 PyEval_CallObject(pFunc, NULL); } else { cout << "cannot find function a" << endl; } } else { cout << "cannot find Life.py" << endl; } }
//調(diào)用一參數(shù)函數(shù)
void InvokeWith2Parm() { PyObject* pMod = NULL; PyObject* pFunc = NULL; PyObject* pParm = NULL; PyObject* pRetVal = NULL; int iRetVal = 0; //導(dǎo)入模塊 pMod = PyImport_ImportModule("FuncDef"); if(pMod) { pFunc = PyObject_GetAttrString(pMod, "square"); if(pFunc) { //創(chuàng)建參數(shù) pParm = Py_BuildValue("(i)", 5); //函數(shù)調(diào)用 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; } }
//調(diào)用多參數(shù)函數(shù)
void InvokeWith3Parm() { PyObject* pMod = NULL; PyObject* pFunc = NULL; PyObject* pParm = NULL; PyObject* pRetVal = NULL; int iRetVal = 0; //導(dǎo)入模塊 pMod = PyImport_ImportModule("add"); if(pMod) { pFunc = PyObject_GetAttrString(pMod, "add"); if(pFunc) { //創(chuàng)建兩個(gè)參數(shù) pParm = PyTuple_New(2); //為參數(shù)賦值 PyTuple_SetItem(pParm, 0, Py_BuildValue("i",2000)); PyTuple_SetItem(pParm, 1, Py_BuildValue("i",3000)); //函數(shù)調(diào)用 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(); // 垃圾回收、清除導(dǎo)入庫(kù) return 0; }
看完上述內(nèi)容,你們掌握C++項(xiàng)目中怎么調(diào)用python函數(shù)的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。