您好,登錄后才能下訂單哦!
這篇文章主要介紹“C++項(xiàng)目中如何調(diào)用python函數(shù)”,在日常操作中,相信很多人在C++項(xiàng)目中如何調(diào)用python函數(shù)問(wèn)題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”C++項(xiàng)目中如何調(diào)用python函數(shù)”的疑惑有所幫助!接下來(lái),請(qǐng)跟著小編一起來(lái)學(xué)習(xí)吧!
代碼如下,分別演示直接執(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; }
到此,關(guān)于“C++項(xiàng)目中如何調(diào)用python函數(shù)”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)?lái)更多實(shí)用的文章!
免責(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)容。