C++項(xiàng)目中怎么調(diào)用python函數(shù),相信很多沒有經(jīng)驗(yàn)的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。
成都創(chuàng)新互聯(lián)公司堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:網(wǎng)站制作、成都網(wǎng)站建設(shè)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時代的郯城網(wǎng)站設(shè)計(jì)、移動媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!
代碼如下,分別演示直接執(zhí)行python語句、無返回?zé)o參數(shù)函數(shù)調(diào)用、返回單參數(shù)函數(shù)調(diào)用。返回多參數(shù)函數(shù)調(diào)用:
#include#include using namespace std; //執(zhí)行python命令 void ExecPythonCommand() { //直接執(zhí)行 PyRun_SimpleString("from time import time,ctime\n" "print 'Today is',ctime(time())\n"); } //調(diào)用無參數(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)建兩個參數(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)入庫 return 0; }
看完上述內(nèi)容,你們掌握C++項(xiàng)目中怎么調(diào)用python函數(shù)的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!