1. 參數(shù)傳遞
參數(shù)傳遞的意思就是將 C 的值傳遞給 py 的函數(shù),然后進(jìn)行計(jì)算輸出。
- 將數(shù)據(jù)值從C轉(zhuǎn)換為Python,
- 使用轉(zhuǎn)換后的值對Python接口例程執(zhí)行函數(shù)調(diào)用
- 將數(shù)據(jù)值從Python調(diào)用轉(zhuǎn)換為C。
2. 例子
第二個(gè)程序的目標(biāo)是在Python腳本中執(zhí)行一個(gè)函數(shù),現(xiàn)在這里需要傳遞參數(shù)。與關(guān)于非常高級接口的部分一樣,Python解釋器并不直接與應(yīng)用程序交互(但這將在下一節(jié)中進(jìn)行更改)。
運(yùn)行Python腳本中定義的函數(shù)的代碼是:
#define PY_SSIZE_T_CLEAN #include#include int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); PyObject *pName, *pModule, *pFunc; PyObject *pArgs, *pValue; int i; if (argc < 3) { fprintf(stderr,"用法: call pythonfile funcname [args]\n"); return 1; } Py_Initialize(); //初始化 Py 解釋器 PyRun_SimpleString("import sys\n"); PyRun_SimpleString("print(sys.path.append('/Users/wangxinnian/Downloads/qtApp/testQP2'))\n"); pName = PyUnicode_DecodeFSDefault(argv[1]); /* Error checking of pName left out */ pModule = PyImport_Import(pName); Py_DECREF(pName); if (pModule != nullptr) { pFunc = PyObject_GetAttrString(pModule, argv[2]); /* pFunc is a new reference */ if (pFunc && PyCallable_Check(pFunc)) { pArgs = PyTuple_New(argc - 3); for (i = 0; i < argc - 3; ++i) { pValue = PyLong_FromLong(atoi(argv[i + 3])); if (!pValue) { Py_DECREF(pArgs); Py_DECREF(pModule); fprintf(stderr, "不能轉(zhuǎn)化參數(shù)\n"); return 1; } /* pValue reference stolen here: */ PyTuple_SetItem(pArgs, i, pValue); } pValue = PyObject_CallObject(pFunc, pArgs); Py_DECREF(pArgs); if (pValue != nullptr) { printf("Result of call: %ld\n", PyLong_AsLong(pValue)); Py_DECREF(pValue); } else { Py_DECREF(pFunc); Py_DECREF(pModule); PyErr_Print(); fprintf(stderr,"Call failed\n"); return 1; } } else { if (PyErr_Occurred()) PyErr_Print(); fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]); } Py_XDECREF(pFunc); Py_DECREF(pModule); } else { PyErr_Print(); fprintf(stderr, "Failed to load \"%s\"\n", argv[1]); return 1; } if (Py_FinalizeEx() < 0) { return 120; } return a.exec(); }
3.添加py 文件multiply.py
# This Python file uses the following encoding: utf-8 # if__name__ == "__main__": # pass def multiply(a,b): print("Will compute", a, "times", b) c = 0 for i in range(0, a): c = c + b return c
4.計(jì)算結(jié)果
$ testQP2 multiply multiply 5 6
None
Will compute 5 times 6
Result of call: 30
5 總結(jié)
雖然該程序的功能相當(dāng)大,但是大部分代碼用于Python和C之間的數(shù)據(jù)轉(zhuǎn)換以及錯(cuò)誤報(bào)告。
初始化解釋器之后,使用PyImport_Import()加載腳本。這個(gè)例程需要一個(gè)Python字符串作為參數(shù),它是使用PyUnicode_FromString()數(shù)據(jù)轉(zhuǎn)換例程構(gòu)造的。
加載腳本之后,使用PyObject_GetAttrString()檢索我們要查找的名稱。如果名稱存在,并且返回的對象是可調(diào)用的,則可以安全地假設(shè)它是一個(gè)函數(shù)。然后程序按照正常方式構(gòu)造一個(gè)參數(shù)元組。然后用以下方法調(diào)用Python函數(shù)。
在函數(shù)返回時(shí),pValue要么為NULL,要么包含對函數(shù)返回值的引用。請確保在檢查值之后釋放引用。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
