1. 參數傳遞
參數傳遞的意思就是將 C 的值傳遞給 py 的函數,然后進行計算輸出。
- 將數據值從C轉換為Python,
- 使用轉換后的值對Python接口例程執行函數調用
- 將數據值從Python調用轉換為C。
2. 例子
第二個程序的目標是在Python腳本中執行一個函數,現在這里需要傳遞參數。與關于非常高級接口的部分一樣,Python解釋器并不直接與應用程序交互(但這將在下一節中進行更改)。
運行Python腳本中定義的函數的代碼是:
#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, "不能轉化參數\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.計算結果
$ testQP2 multiply multiply 5 6
None
Will compute 5 times 6
Result of call: 30
5 總結
雖然該程序的功能相當大,但是大部分代碼用于Python和C之間的數據轉換以及錯誤報告。
初始化解釋器之后,使用PyImport_Import()加載腳本。這個例程需要一個Python字符串作為參數,它是使用PyUnicode_FromString()數據轉換例程構造的。
加載腳本之后,使用PyObject_GetAttrString()檢索我們要查找的名稱。如果名稱存在,并且返回的對象是可調用的,則可以安全地假設它是一個函數。然后程序按照正常方式構造一個參數元組。然后用以下方法調用Python函數。
在函數返回時,pValue要么為NULL,要么包含對函數返回值的引用。請確保在檢查值之后釋放引用。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

